I can't make any of these to work and I am not sure how to use them.
Here is an example that I would like to use to teach myself how to work with these debuggers
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include<iostream>
int main()
{
int *mem;
for (int i=0; i<10; ++i)
{
mem = newint[10]; // memory leak
for (int i=0; i<10; ++i)
mem[i] = i;
for (int i=0; i<10; ++i)
std::cout << mem[i] << ' ';
std::cout << std::endl;
}
return 0;
}
// Top of file where main() is called.
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#ifdef _DEBUG
#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
#define new DEBUG_NEW
#endif
I assume that it will work for this simple example that I wrote earlier. But how about something more complicated? If I have my code in many different files (both headers and source files) what then? I don't want to go over every single one of them and write this preprocessor directives. Is there an easier way?
It seems that I have a lot to learn about c++.
What are you saying? If I declare these directives in the file where main() is called than no matter where I use new (even if it is another source file) it will know to dump memory leaks into a file?
It will report memory leaks when the program exits, so you can fix them. It won't do it for you.
(And yes, regardless of which file contains the code that generates them. The compiler laughs at your multi-file design anyway.)
You don't need to do anything special to use valgrind. Just call it for a debug build of your program as follows: valgrind --leak-check=full ./yourProject
It will then give you output such as this:
==3053== Memcheck, a memory error detector
==3053== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
==3053== Using Valgrind-3.6.1 and LibVEX; rerun with -h for copyright info
==3053== Command: ./yourProject
==3053==
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
==3053==
==3053== HEAP SUMMARY:
==3053== in use at exit: 400 bytes in 10 blocks
==3053== total heap usage: 10 allocs, 0 frees, 400 bytes allocated
==3053==
==3053== 400 bytes in 10 blocks are definitely lost in loss record 1 of 1
==3053== at 0x4C28658: operator new[](unsigned long) (vg_replace_malloc.c:305)
==3053== by 0x400861: main (main.cpp:9)
==3053==
==3053== LEAK SUMMARY:
==3053== definitely lost: 400 bytes in 10 blocks
==3053== indirectly lost: 0 bytes in 0 blocks
==3053== possibly lost: 0 bytes in 0 blocks
==3053== still reachable: 0 bytes in 0 blocks
==3053== suppressed: 0 bytes in 0 blocks
==3053==
==3053== For counts of detected and suppressed errors, rerun with: -v
==3053== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4)
This tells you that a total of 400 bytes have been leaked by the new[] in line 9 of main.cpp.