2

I'd like to track down when and how much memory gets allocated in my program and print it out for debugging purposes under certain circumstances!

  • How can I print out a message with the allocated memory amount every time new is used to allocate memory in my program?
0

4 Answers 4

4

An excellent way to debug memory problems is to use an external monitor such as valgrind. This will hook into the memory allocation and deallocation of your program, and print out a report at the end of your program showing any allocations that you didn't deallocate. No modification or recompilation of your program is necessary with this method.

3

You could overload the new and delete operators. See this article.

1
  • This is risky, depending on how 3rd party libraries are assuming handling of new and delete. If you can, localise your overloads to the types you need to track, rather than the global operator new/delete.
    – Keith
    Feb 9, 2011 at 23:48
2

You can use malloc hooks to do this if you are using the GNU glibc library, which would be a better way to do it than overloading new/delete, assuming you want to capture all allocations within your program. If you just want to capture allocations using new/delete, then you can overload those operators.

By the way, if you are trying to detect and debug memory issues, then rather than rolling your own system, you would probably benefit from using valgrind with memcheck.

0

If your application is really simple, you can try this. Else follow using valgrind as others suggested.

int sum = 0;

class foo
{
    int a,b,c;
};   

int main()
{
    foo *obj1 = new foo;

    sum += sizeof(*obj1); // 12 bytes

    foo *obj2 = new foo;

    sum += sizeof(*obj2); // 24 bytes

    std::cout << " \n Total memory allocated with new:\t " << sum << std::endl ;
    return 0;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.