Linux Allocator Does Not Release Small Chunks of Memory

This behaviour is intentional, there is a tunable threshold that glibc uses to decide whether to actually return memory to the system or whether to cache it for later reuse. In your first program you make lots of small allocations with each push_back and those small allocations are not a contiguous block and are presumably below the threshold, so don’t get returned to the OS.

Calling malloc_trim(0) after clearing the list should cause glibc to immediately
return the top-most region of free memory to the system (requiring a sbrk system call next time memory
is needed.)

If you really need to override the default behaviour (which I wouldn’t recommend unless profiling reveals it actually helps) then you should probably use strace and/or experiment with
mallinfo to
see what’s actually happening in your program, and maybe using mallopt to
adjust the threshold for returning memory to the system.

Leave a Comment