Does realloc() invalidate all pointers?

531 views Asked by At

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?

4

There are 4 answers

0
Sourav Ghosh On BEST ANSWER

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.

0
P.P On

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

Yes. realloc doesn't affect other pointers/memory allocations you did.

Note that the method of realloc:

ptr = realloc(ptr, ...);

is not safe if realloc fails. See Does realloc overwrite old contents?

0
dlask On

ptr2 is not affected by realloc of ptr1.

0
saurabh agarwal On

If Memory is available behind the heap realloc allocates that. If not, It is like malloc a block of the new size, It memcpy your content there.