开发者

C++: "Watch" usage of "new", "delete" operators

I'd like to track down when and how much memory gets allocated in my program and print开发者_StackOverflow中文版 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?


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.


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


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.


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜