Valgrind can be used to find memory leakage. Valgrind is a multipurpose code profiling and memory debugging tool for Linux when on the x86 and, as of version 3, AMD64, architectures.
Below is the example on how to use valgrind:
#include
int main()
{
char *x = malloc(100); /* or, in C++, “char *x = new char[100] */
return 0;
}
int main()
{
char *x = malloc(100); /* or, in C++, “char *x = new char[100] */
return 0;
}
% valgrind –tool=memcheck –leak-check=yes example1
This will result in some information about the program showing up, culminating in a list of calls to malloc
that did not have subsequent calls to free:
that did not have subsequent calls to free:
==2116== 100 bytes in 1 blocks are definitely lost in loss record 1 of 1
==2116== at 0×1B900DD0: malloc (vg_replace_malloc.c:131)
==2116== by 0×804840F: main (in /home/cprogram/example1)
==2116== at 0×1B900DD0: malloc (vg_replace_malloc.c:131)
==2116== by 0×804840F: main (in /home/cprogram/example1)
This doesn’t tell us quite as much as we’d like, though — we know that the memory leak was caused
by a call to malloc in main, but we don’t have the line number. The problem is that we didn’t compile
using the -g option of gcc, which adds debugging symbols. So if we recompile with debugging symbols,
we get the following, more useful, output:
by a call to malloc in main, but we don’t have the line number. The problem is that we didn’t compile
using the -g option of gcc, which adds debugging symbols. So if we recompile with debugging symbols,
we get the following, more useful, output:
==2330== 100 bytes in 1 blocks are definitely lost in loss record 1 of 1
==2330== at 0×1B900DD0: malloc (vg_replace_malloc.c:131)
==2330== by 0×804840F: main (example1.c:5)
==2330== at 0×1B900DD0: malloc (vg_replace_malloc.c:131)
==2330== by 0×804840F: main (example1.c:5)
Comments
Post a Comment