Can anyone summarize what is the correct usage of realloc()
?
What do you do when realloc()
fails?
From what I have seen so far, it seems that if realloc()
fails, you have to free()
old pointer. Is that true?
Here is an example:
1. char *ptr = malloc(sizeof(*ptr) * 50);
2. ...
3. char *new_ptr = realloc(ptr, sizeof(*new_ptr) * 60);
4. if (!new_ptr) {
5. free(ptr);
6. return NULL;
7. }
Suppose realloc()
fails on line 3
. Am I doing the right thing on line 5
by free()
ing ptr
?
If size is 0, the realloc() function returns NULL. If there is not enough storage to expand the block to the given size, the original block is unchanged and the realloc() function returns NULL. The storage to which the return value points is aligned for storage of any type of object.
If realloc() fails the original block is left untouched; it is not freed or moved.
If realloc fails, it returns null pointer, but it doesn't deallocate the old memory.
W.r.t failure realloc and malloc are almost equal. The only reason that realloc may fail additionally is that you give it a bad argument, that is memory that had not been allocated with malloc or realloc or that had previously been free d.
From http://www.c-faq.com/malloc/realloc.html
If realloc cannot find enough space at all, it returns a null pointer, and leaves the previous region allocated.
Therefore you would indeed need to free the previously allocated memory still.
It depends on what you want to do. When realloc
fails, what is it you want to do: free the old block or keep it alive and unchanged? If you want to free it, then free it.
Keep in mind also, that in C89/90 if you make a realloc
request with zero target size, realloc
function may return a null pointer even though the original memory was successfully deallocated. This was a defect in C89/90, since there was no way to tell the success from failure on null return.
In C99 this defect was fixed and the strict relationship between null return and success/failure of reallocation was guaranteed. In C99 null return always means total failure of realloc
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With