memory leak unit test c++

2019-04-09 01:57发布

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), before 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?

6条回答
Lonely孤独者°
2楼-- · 2019-04-09 02:09

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.

查看更多
姐就是有狂的资本
3楼-- · 2019-04-09 02:13

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.

查看更多
欢心
4楼-- · 2019-04-09 02:13
Summer. ? 凉城
5楼-- · 2019-04-09 02:16

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.

查看更多
Root(大扎)
6楼-- · 2019-04-09 02:19

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.

查看更多
甜甜的少女心
7楼-- · 2019-04-09 02:25

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.

查看更多
登录 后发表回答