Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

c++ - 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!
");

sleep(10);
printf("endend
");

Thanks you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...