开发者

memory leak unit test c++

开发者 https://www.devze.com 2023-01-13 11:04 出处:网络
I have just resolved a memory leak in my application and now I want to write a unit test to ensure that this does not happen again.

I have just resolved a memory leak in my application and now I want to write a unit test to ensure that this does not happen again.

I'm look for a way to detect the memory usage of the current application (working set), befor开发者_JS百科e and after some functions.

For example:

long mem_used= GetMemUsed(); 
/* Do some work */
/* clean up */

if( mem_used != GetMemUsed() ) {
    Error( "Memory leek" ); 
}

I have found plenty of ways to detect the memory usage across the entire system but none for just the current application.

Suggestions, links, code snippets?


Boost.Test will automatically tell you at the end of a test run if any of your unit tests leaked memory.

I don't know if any of the other C++ unit testing frameworks provide this kind of functionality.


I really like ValGrind for this sort of thing. These tools already exist; you don't need to write your own unit tests to detect memory leaks.


For Linux or other systems that use GLibC there are functions to get memory allocation statistics. Assuming no lazy allocations, you should have the same memory committed to malloc before and after you perform your test.


That is not a unit test. If you want to make sure some unit that is supposed to manage a resource does not leak that resource then you need to validate that the resource it is managing gets deleted at the correct times. You can do this with mock objects which increment a counter on construction and decrement on delete...then make sure the count is right.

A test that checks the memory usage of an entire application is not something for a unit test. Unit tests are for particular units within the application.


You can also use google test framework (gtest) and then use google performance tools (gperf) to find leaks. GPerf puts in a replacement memory library and if there is a memory leak found after the test run completes it will let you know and gives you a pprof command to run with several different output formats - text, dot, web, etc. This tool will find leaks in both tests and production code.

I also use Valgrind to confirm if there is a leak when questionable but prefer gperf. One gotcha is that if you have compiled with the gperf memory library and try to use Valgrind, it won't find any issues because it catches the leaks so you need to clean compile between switching or have a second copy of the project.


ProcessExplorer (http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) works well for that.

0

精彩评论

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