开发者

Memory leak in c++

开发者 https://www.devze.com 2023-02-14 07:57 出处:网络
How to detect memory leak. I mean is there any tool/utility available or any piece of code (i.e. overloading of operator new and delete)or just i need to check the new and delete in the code??

How to detect memory leak. I mean is there any tool/utility available or any piece of code (i.e. overloading of operator new and delete) or just i need to check the new and delete in the code??

If there any tool/utility is there please tell me. and if code is there then what is the code can an开发者_JS百科y one explain?


Tools that might help you:
Linux: valgrind
Win32: MemoryValidator

You have to check every bit of memory that gets allocated (new, malloc, ...) if it get's freed using the appropriate function (delete, free, ...).


  • Use e.g. boost:shared_ptr instead of naked pointers.
  • Analyze your application with one of these: http://en.wikipedia.org/wiki/Memory_debugger


One way is to insert file name and line number strings (via pointer) of the module allocating memory into the allocated block of data. The file and line number is handled by using the C++ standard "FILE" and "LINE" macros. When the memory is de-allocated, that information is removed.

One of our systems has this feature and we call it a "memory hog report". So anytime from our CLI we can print out all the allocated memory along with a big list of information of who has allocated memory. This list is sorted by which code module has the most memory allocated. Many times we'll monitor memory usage this way over time, and eventually the memory hog (leak) will bubble up to the top of the list.


valgrind is a very powerful tool that you can use to detect memory leaks. Once installed, you can run

valgrind --leak-check=full path/to/program arguments...

and valgrind will run the program, finding leaks and reporting them to you.


I can also recommend UMDH: http://support.microsoft.com/kb/268343


Your best solution is probably to use valgrind, which is one of the better tools.

If you are running in OS X with Xcode, you can use the Leaks tool. If you click Run with performance tool and select Leaks, it will show allocated and leaked memory.

Something to remember though. Most of the tools listed only describe tools that catch memory leaks as they occur. So if you have some code that leaks memory but is rarely called (or rarely enough that you don't encounter it when testing for memory leaks), then you could miss it. If you want something that actually runs through your code, you'll need a static analyzer. The only one I know of is the Clang Static Analyzer, but it is for C and Obj-C (I don't know if it supports C++).

0

精彩评论

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