Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memory leak unit test c++

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?

like image 758
Steven Smethurst Avatar asked Aug 24 '10 18:08

Steven Smethurst


3 Answers

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.

like image 82
Ferruccio Avatar answered Nov 16 '22 17:11

Ferruccio


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.

like image 44
Ed S. Avatar answered Nov 16 '22 17:11

Ed S.


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.

like image 4
doron Avatar answered Nov 16 '22 17:11

doron