Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding memory allocation method standard libraries use? [duplicate]

Is it possible to override the way STL allocates, manages, and frees memory? How would one do so, if it's possible? Is there a way to do this in a way that keeps the code that handles the raw memory in one class or file?

I would like to do this for my entire program so I can keep track of memory usage, timing, and lifetime info. Purely out of curiousity of course!

like image 564
Anne Quinn Avatar asked Sep 14 '25 10:09

Anne Quinn


2 Answers

You can do that by redefining the operators new and delete in one of your files.

The linker will override the standard ones by yours when resolving symbols.

You'll find lots and lots of answers on SO, like this one: overloading new/delete or that one: How to track memory allocations in C++ (especially new/delete) .

There exist some libraries on the internet that do that for you as well, like Memtrack or this one . SO has also some resources on that: C++ memory leak auto detection library .

like image 196
Gui13 Avatar answered Sep 16 '25 01:09

Gui13


Standard Library classes that manage data with dynamic storage duration take an allocator as one of their template arguments. The class will then make calls to an instance of the allocator for memory management. For instance you can do std::vector<int, MyAllocator> somevec; or std::list<Node*, MyAllocator> someList; to provide custom allocators to containers.

Here is an SO Q&A about allocators. The answer the link goes to includes skeleton code for an allocator that should be a good starting point for you.

like image 20
Captain Obvlious Avatar answered Sep 16 '25 03:09

Captain Obvlious