Falcata
Falcata

Reputation: 707

How to make a pointer to a pointer NULL

I am trying to make the last element in an array of pointers a NULL but I am having some problems. My code is as follows:

kernel->availMsgEnvQueue = (MsgEnv *)malloc(AVAIL_MSG_ENV_SIZE * sizeof(MsgEnv));
int i;
for(i=0; i<AVAIL_MSG_ENV_SIZE-1; i++)
     {
    kernel->availMsgEnvQueue[i].nextMsgEnv = &(kernel->availMsgEnvQueue[i+1]);
    kernel->availMsgEnvQueue[i].msg = (Msg)malloc(MSG_SIZE * sizeof(char));
}
kernel->availMsgEnvQueue[19].nextMsgEnv = NULL;

Where AVAIL_MSG_ENV_SIZE is 20. I am trying to make the 20th element a null but this is not working as I am getting a segmentation fault when I run the following to test:

while (kernel->availMsgEnvQueue->nextMsgEnv) 
     {
    printf ("%d\n", x);
    temp = temp->nextMsgEnv;
    x++;
}

X counts all the way upto 20 and then it crashes. Please assist.


EDIT : Apparantly the last element in the list is being sent to zero. I can't figure out if this code will dequeue the last message envelope from the queue::

MsgEnv * k_request_msg_env (){
    MsgEnv * env = kernel->availMsgEnvQueue->nextMsgEnv;
    if(!env){
        printf ("This one was null");
        PCB * pcb = kernel->current_process;
        if(pcb->state != IS_IPROCESS){
            printf ("Process %d is being blocked on request",pcb->id);
            pcb->state = BLOCK_ON_ENV;
            enPQ(kernel->bq, pcb, pcb->priority);
            k_process_switch();
        }
    }else{
        kernel->availMsgEnvQueue->nextMsgEnv = kernel->availMsgEnvQueue->nextMsgEnv->nextMsgEnv;
        env->nextMsgEnv = NULL;

        //clear message
        memset(env->msg, 0, MSG_SIZE);
    }
    return env;
}

Thanks!

Upvotes: 1

Views: 201

Answers (1)

Mysticial
Mysticial

Reputation: 471199

Your loop-test doesn't change:

while (kernel->availMsgEnvQueue->nextMsgEnv) {

So it's iterating through 20 times, and keeps on going...

Perhaps you meant this?

while (kernel->availMsgEnvQueue[x].nextMsgEnv) {

Upvotes: 2

Related Questions