Question

If I try to use realloc to allocate less memory for a pointer than it initially had allocated, will the redundant memory be freed or will the reallocation result in a memory leak?

I don't know how I could test this, sizeof seems to return the same value independent of how many re-allocations I do.

Was it helpful?

Solution

The definition of a memory leak is: memory you can no longer free since you lost all pointers ("handles") to it. Since realloc() returns a pointer to the possibly moved location, it doesn't create a leak in this sense. Whether the excess memory after shrinking is available for further allocations is an implementation detail of your particular library.

Note however that you can in fact easily create a memory leak with realloc if you don't use a temporary variable:

m = realloc (m, size);  /* Potential memory leak. */

If realloc returns NULL, you've lost the previous value of m (okay, we're out of memory, so a memory leak is just another problem now, but still). I recommend to get into the habit of writing

 t = realloc (m, size);
 if (t != NULL)
    m = t;
 else
    deal_with_out_of_memory_situation ();

Note that sizeof never yields the size of allocated memory, but always the size of the object (which for pointers to allocated memory is the size of the pointer, not the size of pointed to memory.)

OTHER TIPS

The whole point of malloc and realloc is that you get memory which you can free without leaking (if you use it properly). So using realloc as you describe is correct and won't leak.

The docs don't explicitly say this but the implication is using these functions result in correct allocation and freeing of memory. Otherwise there would be no reason for the functions to exist.

realloc() changes the size of the memory block pointed to by ptr to size bytes. The contents will be unchanged to the minimum of the old and new sizes; newly allocated memory will be uninitialized. If ptr is NULL, the call is equivalent to malloc(size); if size is equal to zero, the call is equivalent to free(ptr). Unless ptr is NULL, it must have been returned by an earlier call to malloc(), calloc() or realloc(). If the area pointed to was moved, a free(ptr) is done.

http://unixhelp.ed.ac.uk/CGI/man-cgi?realloc+3

From the man :

realloc() creates a new allocation, copies as much of the old data pointed to by ptr as will fit to the new allocation, FREES THE OLD ALLOCATION, and returns a pointer to the allocated memory.

So I don't think it will result in a memory leak

realloc() intern frees the old memory allocation pointed to by the pointer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top