How do I test for/track memory leaks in a CLI/CPP library?

Hi:

I've got a CLI/CPP wrapper library which wraps a native C++ library.
That wrapper is then available to be consumed by .Net (managed) clients.

I'm about to start testing for memory leaks for objects created in the CLI/C++ layer.

What is the best way to test for memory leaks?

Will something like Video Leak Detector catch leaked memory allocated in the CLI/C++ layer?

Is there another tool I should be using or another way to tackle this?

Thanks,
JohnB
LVL 1
jxbmaSoftware ConsultantAsked:
Who is Participating?
 
jkrCommented:
You can do that with the CRT's Debug APIs, e.g. like

int tmpFlag;

// Get the current state of the flag
// and store it in a temporary variable
tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );

// Turn On (OR) - Keep freed memory blocks in the
// heap’s linked list and mark them as freed
tmpFlag |= _CRTDBG_LEAK_CHECK_DF;
tmpFlag |= _CRTDBG_CHECK_ALWAYS_DF;
tmpFlag |= _CRTDBG_ALLOC_MEM_DF;
tmpFlag |= _CRTDBG_DELAY_FREE_MEM_DF;

// Set the new state for the flag
_CrtSetDbgFlag( tmpFlag );

test(); // code that interacts with .NET

_CrtDumpMemoryLeaks ();

Open in new window


Or, since your code resides in a DLL:

BOOL WINAPI DllMain(
  _In_  HINSTANCE hinstDLL,
  _In_  DWORD fdwReason,
  _In_  LPVOID lpvReserved
  ) {

    int tmpFlag;

    switch (fdwReason) {

        case DLL_PROCESS_ATTACH: // DLL is loaded

            // Get the current state of the flag
            // and store it in a temporary variable
            tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );

            // Turn On (OR) - Keep freed memory blocks in the
            // heap’s linked list and mark them as freed
            tmpFlag |= _CRTDBG_LEAK_CHECK_DF;
            tmpFlag |= _CRTDBG_CHECK_ALWAYS_DF;
            tmpFlag |= _CRTDBG_ALLOC_MEM_DF;
            tmpFlag |= _CRTDBG_DELAY_FREE_MEM_DF;

            // Set the new state for the flag
            _CrtSetDbgFlag( tmpFlag );

            break;

        case DLL_PROCESS_DEACH: // DLL is unloaded

            _CrtDumpMemoryLeaks ();

            break;
    }

    return TRUE;
}

Open in new window


The information provided by '_CrtDumpMemoryLeaks()' will even include the line numbers where the allocations where made. See also https://msdn.microsoft.com/en-us/library/x98tx3cf.aspx ("Finding Memory Leaks Using the CRT Library")
0
 
jxbmaSoftware ConsultantAuthor Commented:
Spot on again man!
Thanks so much,
JB
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.