Using realloc to shrink the allocated memory
No, you won't have a memory leak. realloc
will simply mark the rest "available" for future malloc
operations.
But you still have to free
myPointer
later on. As an aside, if you use 0
as the size in realloc
, it will have the same effect as free
on some implementations. As Steve Jessop and R.. said in the comments, you shouldn't rely on it.
There is definitely not a memory leak, but any of at least 3 things could happen when you call realloc
to reduce the size:
- The implementation splits the allocated memory block at the new requested length and frees the unused portion at the end.
- The implementation makes a new allocation with the new size, copies the old contents to the new location, and frees the entire old allocation.
- The implementation does nothing at all.
Option 3 would be a rather bad implementation, but perfectly legal; there's still no "memory leak" because the whole thing will still be freed if you later call free
on it.
As for options 1 and 2, which is better depends a lot on whether you favor performance or avoiding memory fragmentation. I believe most real-world implementations will lean towards doing option 1.
The new code still leaks the original allocation if the realloc fails. I expect most implementations won't ever fail to shrink a block, but it's allowed. The correct way to call realloc, whether growing or shrinking the block, is void *tmp = realloc(myPointer, 50*sizeof(int)); if (!tmp) { /* handle error somehow. myPointer still points to the old block, which is still allocated */ } myPointer = tmp;. – Steve Jessop 48 mins ago
Hey, I couldn't figure out how to reply to your comment, sorry.
Do I need to cast tmp to the type of myPointer? In this case, do I need to write
myPointer = (int*)tmp
Also, in this case, when I do free(myPointer) The memory pointed at by tmp will be freed as well, right? So no need to do
free(myPointer)
free(tmp)