Search code examples
cpointersrealloc

Does realloc() invalidate all pointers?


Note, this question is not asking if realloc() invalidates pointers within the original block, but if it invalidates all the other pointers.

I am a bit confused about the nature of realloc(), specifically if it moves any other memory.

For example:

void* ptr1 = malloc(2);
void* ptr2 = malloc(2);
....
ptr1 = realloc(ptr1, 3);

After this, can I guarantee that ptr2 points to the same data it did before the realloc() call?


Solution

  • Yes, ptr2 is unaffected by realloc(), it has no connection to realloc() call whatsoever(as per the current code).

    However, FWIW, as per the man page of realloc(), (emphasis mine)

    The realloc() function returns a pointer to the newly allocated memory, which is suitably aligned for any kind of variable and may be different from ptr,

    ptr1 is likely to be changed.

    That said,

     ptr1 = realloc(ptr1, 3);
    

    style is very dangerous. In case realloc() fails,

    The realloc() function returns .... or NULL if the request fails

    and

    If realloc() fails the original block is left untouched; it is not freed or moved.

    but, as per your statement, in failure case the NULL return will overwrite the actual memory, losing the actual memory and creating memory leak.