Why does the free() function not return memory to the operating system?

Memory is allocated onto a heap.

When you request some memory in your program (with a new() or malloc() etc.) Your program requests some memory from its heap, which in turn requests it from the operating system{1}. Since this is an expensive operation, it gets a chunk of memory from the OS, not just what you ask for. The memory manager puts everything it gets into the heap, just returning to you the perhaps small amount you asked for. When you free() or delete() this memory, it simply gets returned to the heap, not the OS.

It’s absolutely normal for that memory to not be returned to the operating system until your program exits, as you may request further memory later on.

If your program design relies on this memory be recycled, it may be achievable using multiple copies of your program (by fork()~ing) which run and exit.

{1} The heap is probably non-empty on program start, but assuming it’s not illustrates my point.

Leave a Comment