views:

58

answers:

1

How does relloc behaves when it has to resize the allocated memory to a bigger size and it has to be done in a separate memory area as the requested amount of memory can be resized inplace. Does the original memory is deallocated automatically by relloc (I would think so ) or it has to be done by the programmer (not likely) ?

+2  A: 

Yes, realloc automatically handles freeing the original memory. If the memory block can be resized in place, then realloc will do so. If not, it will allocate a new memory block that is large enough, copy the data from the old block to the new, and free the old block. You don't have to worry about freeing it yourself.

If realloc fails (e.g. you asked for way too much memory, and it couldn't allocate that much), then the original memory is NOT freed. If you're not careful, you can leak memory -- if realloc returns NULL due to a failure and you don't keep a pointer to the original memory block, that memory will remain allocated and leak.

Adam Rosenfield