Handmade Hero»Forums»Code
3 posts
I'm in need of help detecting memory leaks.
I'm a college student and in class we have learned about dynamically allocating arrays. I'm trying to learn how to detect for memory leaks but when i compile from the command line and run the application with debugging on i don't get a MEMORY LEAK DETECTED or anything of the sort. My code below to test for a memory leak:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#define _CRTDBG_MAP_ALLOC

#include <crtdbg.h> //place at end of all #include

int main()
{
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

	int * int_ptr = new int;
	int_ptr = 0;

	//delete int_ptr; 

	return(0);
}


If i compile and run with debugging in visual studio i do not get the memory error. the error should look something like this:

Detected memory leaks!
Dumping objects ->
{163} normal block at 0x002DD6E0, 4 bytes long.
Data: < > CD CD CD CD
Object dump complete.

If i create a win32 console application with the IDE itself and do the exact same thing i do get the memory leak detected. I would like to know if there is some compiler switch that i am missing or something else that i need to do. I like using Sublime Text 2 as my text editor and it would be a shame to open a new win32 console app from visual studio itself every time i want to check.

My build.bat file:
@echo off

echo Compilation Started %date% -%time%
IF NOT EXIST ..\build mkdir ..\build
pushd ..\build
cl -nologo -EHsc -W4 -WX -Zi ..\code\PE_2_WordCount_Lucas_Jones.cpp
popd
echo Compilation Finished %date% -%time%

Please help, I would prefer not to try and fix the color scheme and redo the key bindings in visual studio.
Mārtiņš Možeiko
2568 posts / 2 projects
I'm in need of help detecting memory leaks.
I have found builtin MSVC memory leak detection functionality not very good. I strongly recommend using Visual Leak Detector if you are on Windows. It provides information about leaks in much nicer way.

Anyway, to use _CrtSetDbgFlag function check out what documentation says about it:
When _DEBUG is not defined, calls to _CrtSetDbgFlag are removed during preprocessing.

Probably project you created in MSVC had this define set in properties. Just add it to your commandline: "-D_DEBUG". You'll need also to switch to debug C runtime libraries, because release one (used by default) doesn't have CRT debugging functionality. Add "-MTd" to commandline.