Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using _CrtDumpMemoryLeaks to display data to console

I'm using _CrtDumpMemoryLeaks function which works fine but in the documentation there promised not only to return true or false but also to prints some information.

I tried to use:

_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_DEBUG );

but nothing appear on the screen here some of my code.

#define _CRTDBG_MAP_ALLOC 
#include <stdlib.h>
#include <crtdbg.h>   
#include <stdio.h>
#include <string.h>

int main() {
slist* students = 0;
clist* courses = 0;
char  c;
char  buf[100];
int   id, num;

malloc(100);
_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_DEBUG );


printf("there is memmory leaks?: %d\n",_CrtDumpMemoryLeaks());
system("pause");

return 0;
}

the output has no data about the memory leaks.. why is that?

by the way the output is

there is memmory leaks?: 1 Press any key to continue . . .

like image 854
Yosefki Avatar asked Jan 03 '12 21:01

Yosefki


2 Answers

I have found the following code to be the most useful, particularly as you start isolating the leaks down to particular methods/functions:

// declare memory stare variable
_CrtMemState state;

...

// create a checkpoint to for current memory state
_CrtMemCheckpoint(&state);

... do stuff ...

// report differences
_CrtMemDumpAllObjectsSince(&state);

This routine will dump all allocations since the checkpoint. IT can be wrapped around a function call, loaded on startup and when exiting, etc. I have also used it in a DLL in DllMain process attach/detach.

Also handy when combined with _CrtSetReportMode, _CrtSetReportFile, etc.

like image 144
Tevo D Avatar answered Sep 21 '22 01:09

Tevo D


If you're running this in a Visual Studio 2010 debugging instance, you'll need to look at the Debug Output (Debug -> Windows -> Output).

Moreover, you'll need to set the report mode for not only errors, but also for warnings (which is where memory leaks will be reported):

_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_DEBUG );
/* Alternatively:
 * _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );
 * _CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDERR );
 */

Which presented me the following output for your program:

Detected memory leaks!
Dumping objects ->
dump.c(14) : {86} normal block at 0x00834E50, 100 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.
there is memmory leaks?: 1
like image 26
user7116 Avatar answered Sep 22 '22 01:09

user7116