views:

106

answers:

5

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?

+3  A: 

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.

Ed Swangren
Just make sure it is built into the unit test. Having to run valgrind by hand to validate the application will lead to lazy people not running the test.
Martin York
That sounds like a personnel problem, not a software problem.
Ed Swangren
@Ed: laziness is a person problem, we agree, but since you're forewarned, take it into account and, as Martin suggests, make it so that the easier way to run the test is also the one in which the memory leak detection is built :)
Matthieu M.
Ok, how about kicking it off automatically after a build? It shouldn't be difficult, we have a lot of separate test utilities that we launch after each build for our core input/output modules.
Ed Swangren
A: 

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

Russ
I have been using this tool, but its a manual process this way. I was looking for a way to do it in code so i could add it to a unit test.
Steven smethurst
+4  A: 

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.

Ferruccio
Support for memory leaks only on MS compilers: http://www.boost.org/doc/libs/1_44_0/libs/test/doc/html/execution-monitor/user-guide.html
Martin York
+2  A: 

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.

Noah Roberts
A: 

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.

doron