4

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!

Anne Quinn
  • 12,609
  • 8
  • 54
  • 101
  • Yes... It's pretty difficult... and Yes... Can you achieve the same thing by using `valgrind`? – Alex Chamberlain Apr 26 '13 at 07:31
  • If you're on linux, you can take a look at man (2) brk and sbrk. No idea on windows though. – Nbr44 Apr 26 '13 at 07:31
  • 1
    You have to replace operators `new` and `delete` for that, so run -not walk- to the bookstore and get Chapter 8 of [Effective C++](http://www.amazon.com/Effective-Specific-Improve-Programs-Designs/dp/0321334876) – TemplateRex Apr 26 '13 at 07:34

2 Answers2

7

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 .

Community
  • 1
  • 1
Gui13
  • 12,993
  • 17
  • 57
  • 104
2

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.

Community
  • 1
  • 1
Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74
  • Aw yeah, that's right, I forgot allocators were a template argument. I vaguely remember them being described as complicated affairs to code, but I'll give that a swing – Anne Quinn Apr 26 '13 at 10:41
  • 1
    Actually a basic allocator is quite easy to make. Take a look at the requirements outlined in the link included in my answer. Also here is some skeleton code to create standard library compatible allocator - http://stackoverflow.com/a/12529302/845568 - it should be a decent start for you. – Captain Obvlious Apr 26 '13 at 13:05