|
a command line
free external tools,
java sources
cpp sources
articles
|
How to trace memory leaks C++ with a few lines of code: free source code for instant use in windows projects. starting point: let's say we have a simple C++ program like this:
#include <stdio.h>
#include <string.h>
char *joinStrings(char *p1, char *p2)
{
int nlen1 = strlen(p1);
int nlen2 = strlen(p2);
char *pres = new char[nlen1+nlen2+10];
strcpy(pres, p1);
strcat(pres, p2);
return pres;
}
int main(int argc, char *argv[])
{
printf("string concatenation test:\n");
char *psz1 = "hello";
char *psz2 = "world";
char *pszj = joinStrings(psz1, psz2);
printf("result: %s\n", pszj);
return 0;
}
this program seems to run without problems, producing this output:
string concatenation test: result: helloworldhowever we don't really know if all memory has been freed. to find out, download memdeb.cpp from here and extend the example like this:
#include <stdio.h>
#include <string.h>
#include "memdeb.cpp"
char *joinStrings(char *p1, char *p2)
{
int nlen1 = strlen(p1);
int nlen2 = strlen(p2);
char *pres = new char[nlen1+nlen2+10];
strcpy(pres, p1);
strcat(pres, p2);
return pres;
}
int main(int argc, char *argv[])
{
printf("string concatenation test:\n");
char *psz1 = "hello";
char *psz2 = "world";
char *pszj = joinStrings(psz1, psz2);
printf("result: %s\n", pszj);
listMemoryLeaks();
return 0;
}
now, the program produces this output:
string concatenation test: result: helloworld MEM LEAK: adr 32075ch, size 20, alloc'ed in test.cpp 10 [SMEMDEBUG: 1 new's, 0 delete's, 0 errors, 1 leaks]if you want to integrate the memory tracing into a project with several .cpp files, include it everywhere, defining in most files #define MEMDEB_JUST_DECLAREbefore the include. only in one .cpp file, leave out this define. it should also be easy to split memdeb.cpp into a .hpp and .cpp, as the code is rather short.
NOTE:
#ifdef WITH_MEMORY_TRACING
#include "memdeb.cpp"
#endif
SFK memory tracing is used to track memory leaks in the text file processor swiss file knife. read more about sfk here.
|
|