I highly doubt that anything other than wrapping malloc and free [or new and delete ] with another function can actually get you something other than very rude ratings.
One problem is that freed memory can only be released if there is a long contiguous piece of memory. It usually happens that there are “small bits” of memory that are used throughout the heap, and you cannot find a large chunk that can be freed.
It is very unlikely that you can fix this in any simple way.
And by the way, your application will probably need these 50 MB later, when you will again have more load, so it’s just wasted to free it.
(If the memory you are not using is needed for something else, it will be replaced, and pages that have not been touched for a long time are the first candidates, so if the system runs on low memory for some other tasks, it’s all it will also reuse RAM in your machine for this space, so it doesn’t sit there for nothing - you just can’t use "ps" or some of them to find out how many times your program uses it!)
As suggested in the comment: you can also write your own memory allocator using mmap() to create a “chunk” for extracting parts from. If you have a section of code that does many memory allocations, then ALL of them will surely be freed later to allocate everything from a separate chunk of memory, and when all this is freed, you can put mmap 'd back in the list " free mmap ", and when the list is large enough, free some of the mmap distributions [this is an attempt to avoid calling mmap LOTS times and then munmap again after a few milliseconds]. However, if you ALWAYS allowed one of these memory allocations to “exit” your fenced area, your application will likely crash (or, even worse, not crash, but use memory belonging to some other part of the application, and you get a very strange result somewhere, for example, one user gets access to network content intended for another user!)
source share