Skip to content
Advertisement

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

When I use the top terminal program at Linux, I can’t see the result of free.

My expectation is:

  1. free map and list.

  2. The memory usage that I can see at the top(Linux function) or /proc/meminfo get smaller than past.

  3. sleep is start.

  4. program exit.

But The usage of memory only gets smaller when the program ends.

Would you explain the logic of free function?

Below is my code.

for(mapIter = bufMap->begin(); mapIter != bufMap -> end();mapIter++)
{
    list<buff> *buffList = mapIter->second;
    list<buff>::iterator listIter;
    for(listIter = buffList->begin(); listIter != buffList->end();listIter++)
    {
        free(listIter->argu1);
        free(listIter->argu2);
        free(listIter->argu3);
    }
    delete buffList;
}
delete bufMap;

printf("Free Complete!n");

sleep(10);
printf("endendn");

Thanks you.

Advertisement

Answer

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.

Advertisement