0

I know there are a lot of double pointer questions, but I couldn't find one that pertained to starting an array.

In the code below, I can set pointers in main by ptrs[0] = &array[0];, but the code halts when enqueue() calls *queue[i] = p;. Why is that? I don't know if it matters, but ptrs[] is not initialized.

#define QUEUE_LEN 5

int *ptrs[5];
int array[5] = {1,2,3,4,5};

void enqueue(int *p, int **queue) {
    int i = 0;
    int *tmp;

    // Find correct slot
    while (*queue && *queue[i] >= *p) {
        i++;
    }

    // Error no free slots
    if (i == QUEUE_LEN) {
        printf("No free slots.\r\n");
        return;
    }

    // Insert process
    if (!*queue) {
        *queue[i] = p;
        return;
    }
    else {
        tmp = *queue[i];
        *queue[i] = p;
    }

    // Increment the other processes

    return;
}

int main(int argc, char** argv) {

    int i;
    for (i=0; i<5; i++) {
        enqueue(&array[i], ptrs);
    }

    for (i=0; i<QUEUE_LEN; i++)
        printf("%d\n", *(ptrs[i]));

    return 0;
}
Eric Fossum
  • 2,395
  • 4
  • 26
  • 50
  • Your code outright doesn't compile. In `*queue[i] = p` you are trying to assign a pointer to an integer. – pmr Apr 28 '13 at 16:40
  • Hmm... seems to compile on mine and it was a simple copy paste to here. – Eric Fossum Apr 28 '13 at 17:38
  • Then you should get a proper C compiler or try to crank up the warning level on yours. And even if it does compile, it does not do what you think it does. – pmr Apr 28 '13 at 17:45

2 Answers2

0
// Find correct slot
while (*queue && *queue[i] >= *p) {
    i++;
}

This will access some random memory address taken from uninitialized ptrs value.
Your check for *queue != 0 is not enough, you need to initialize array with zeores as:

int *ptrs[5] = {0};

And you still need to allocate memory you are attempting to write later when inserting.

alexrider
  • 4,449
  • 1
  • 17
  • 27
0

After first loop, i will remain zero. Here:

if (!*queue) {
    *queue[i] = p;
    return;
}

You check, that *queue is 0 and dereference it as well. It is UB.

PS. Btw, this:

*queue[i] = p;

Will not compiles, since *queue[i] has type int, but p has type int*.

awesoon
  • 32,469
  • 11
  • 74
  • 99