General

Tech

Dynamic Memory Allocation

This is regarding realloc specifically and I want clarification on it.

http://pastebin.com/kpsY87su

I am unsure of where the pointers are going to point to exactly when I use realloc (when I get to the end of my array in the heap). When I realloc the array, where is ptr2 going to point to, the beginning of the new array or the current pointer of where ptr1 is at (ie. at spot 50)?

Thanks.

edit: Answer -> ptr2 points to beginning of memory block

March 16, 2013

2 Comments • Newest first

Kuraitou

From the [url=http://linux.die.net/man/3/realloc]man page[/url]:

[quote=realloc3]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, or NULL if the request fails. If size was equal to 0, either NULL or a pointer suitable to be passed to free() is returned. If realloc() fails the original block is left untouched; it is not freed or moved.[/quote]

You want to check ptr2 to ensure that it's not NULL (if it is, ptr1 is still valid), and if it is a valid pointer, you don't need ptr1 anymore. ptr2 will point to the beginning of the block of memory on successful realloc.

Reply March 16, 2013 - edited
AnnaDragon

What exactly does realloc do?

Reply March 16, 2013 - edited