If/When does the does deallocated heap memory get reclaimed?

后端 未结 4 1712
刺人心
刺人心 2021-01-12 21:18

I have been running overnight memory tests on an embedded Linux system. Using vmstat I have observed that the free memory steadily decreases over time. According to some

4条回答
  •  梦谈多话
    2021-01-12 21:57

    User calls to malloc and free (or new and delete), to the best of my knowledge never return no-longer used pages to the O/S. Instead, they just remember what memory has been freed so that if you do a malloc/new of a size that can be satisfied by previously freed memory, then it will use that, rather than going to the O/S and using sbrk to get more memory.

    Thus this code:

    for (;;)
    {
        struct { char data[200 * 1024 * 1024] } HugeBuffer;
        HugeBuffer *buff = new HugeBuffer;
        delete buff;
    }
    

    Will allocate 200Mb once, and then just steadily use that memory forever. It will go to the O/S once on the original allocation, and then loop fiddling around in user space.

提交回复
热议问题