Conversation

In malloc-ng, does realloc to a smaller size return a different pointer? (If you want to be pedantic I am asking about returning a pointer with a different representation, provenance is always different but I'm not asking about that .)
2
The question I was really interested in was whether realloc to a smaller size can return NULL, and I thought that the answer to that was so clearly “obviously not” that I didn't dare ask it, but it seems it is a situation that can arise?
3
3
Since even munmap can fail, realloc to a smaller size can fail for large allocations in any allocator. It's up to them if they report it, but I expect most report it. Most modern allocators use slab allocation. If the size class changes, they need to allocate and copy to that.
2
1
Most modern allocators like jemalloc, mimalloc, hardened_malloc and others use slab allocation with a single size class per slab. They're called runs in jemalloc but it's essentially the same concept. I think musl is a bit more flexible to save space but it still largely applies.
1
It normally wouldn't have a separate code path for shrinking and expanding because it's the same thing with a different copy size. It could special case the error path to essentially leak memory without telling the caller but I don't really expect any malloc implementation does.
1
2
Show replies