Memory usage doesn't decrease when free() used [duplicate]

Solution 1:

On many operating systems, free() doesn't make the memory available for the OS again, but "only" for new calls to malloc(). This is why you don't see the memory usage go down externally, but when you increase the number of new allocations by threading, the memory is re-used so total usage doesn't go through the roof.

Solution 2:

Malloc doesn't have to return memory to the operating system. Most malloc implementations on unix-like systems don't do it. Especially for smaller object sizes.

This is done for performance reasons.

I just noticed that this is potentially unclear. By "malloc" I mean the whole subsystem related to the malloc function - malloc, free, realloc, calloc and whatever special functions your libc might implement.

Solution 3:

To oversimplify things, there are two memory managers at work in dynamic memory allocation: the OS Memory Manager, and the Process Memory Manager (which there can be more than one of). The OS Memory Manager allocates "large chunks" of memory to individual Process Memory Managers. Each Process Memory Manager keeps track of the allocated segments, as well as the "free'd segments". The Process Memory Manager does not return the free'd segments to the OS Memory Manager because it is more efficient to hold on to it, in case it needs to allocate more memory later.