Simple question about the realloc function in C:
If I use realloc to shrink the memory block that a pointer is pointing to, does the “extra” memory get freed? Or does it need to be freed manually somehow?
For example, if I do
int *myPointer = malloc(100*sizeof(int));
myPointer = realloc(myPointer,50*sizeof(int));
free(myPointer);
Will I have a memory leak?
No, you won’t have a memory leak.
reallocwill simply mark the rest “available” for futuremallocoperations.But you still have to
freemyPointerlater on. As an aside, if you use0as the size inrealloc, it will have the same effect asfreeon some implementations. As Steve Jessop and R.. said in the comments, you shouldn’t rely on it.