Alexandre Vanier
Alexandre Vanier

Reputation: 159

How do I detect memory leaks using the tools in CRT in a C++/Java project using JNI?

I've been trying for a few hours now to get it working. So far it does find memory leaks but it finds a ton and I'm not sure if that's realistic. Also I'd like to see the file and line number (I know it's possible but I can't get it to work) so that I can actually solve the memory leaks.

I have added the code to dump memory leaks in a method that is frequently called (about 60 times per second normally), I'm not sure if it's ok or not but since I don't really have a "main" function it's hard to decide where to put the code.

Here is what I have added :

// This part is in the includes part of the file
#define _CRTDBG_MAPALLOC
#define _CRTDBG_MAP_ALLOC_NEW
#include <stdlib.h>
#include <crtdbg.h>

#ifdef _DEBUG
#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
#define new DEBUG_NEW
#endif

// This part is in the method
_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
_CrtDumpMemoryLeaks();

Thanks for the help!

Upvotes: 1

Views: 423

Answers (2)

AlexTheo
AlexTheo

Reputation: 4184

With a crt you have the possibility to compare the memory state before perform an action and after that. In order to achieve this just use the _CrtMemDifference in your unit tests. The concept is to write the unit-tests which will call a different parts of your code and will get the state of the application memory before by using the _CrtMemCheckpoint and after the call. So after that you have to compare two checkpoints with the _CrtMemDifference.

Upvotes: 0

Ich
Ich

Reputation: 1378

Try

Visual Leak Detector

http://www.codeproject.com/Articles/9815/Visual-Leak-Detector-Enhanced-Memory-Leak-Detectio

I had very good results with it.

Upvotes: 1

Related Questions