In common implementations such as Linux/Glibc, Windows/MSVC and BSD/Mac OS X, will
void *p = malloc(N + M); // assume this doesn't fail
p = realloc(p, N); // nor this
for N, M > 0, actually shrink the buffer returned by malloc in the realloc call, in the sense that up to M bytes may return to the free list? And more importantly, is there a chance that it reallocates the buffer?
I want to know because I just implemented dynamic arrays on top of numpy.ndarray, and I’m doing a resize, which calls realloc, to get the final size right. I may be able to skip the final resize as an optimization (at the expense of permanent overallocation) and I want to know if that’s even worth trying.
I can say about Linux/glibc.
In the source code it contains comments like this:
if you look at code of glibc, it contains lines like this:
nb– number of bytes you want,newsizehere, should be calledoldsize.So it tries to free the excess if possible.
About Mac OSX. More precisely about
magazine_malloc, current implementation ofmallocfrom Apple. See http://cocoawithlove.com/2010/05/look-at-how-malloc-works-on-mac.html for details.realloccalls the zone realloc method, its current implementation as I see isszone_realloc.For different allocation sizes exists different code, but the algorithm is always the same:
So as you can see, its implementation checks that
new_size <= old_size / 2, and if so frees memory, and if not it does nothing.