-
Notifications
You must be signed in to change notification settings - Fork 76
Memory check
PAN, Myautsai edited this page Feb 4, 2016
·
2 revisions
We use valgrind to find all memory leaks in C/C++ code.
Suppose there's a leak in but we can't find it:
#include <cstdio>
int main(int argc, const char *argv[]) {
int* xp = new int[3]; // forget to free
return 0;
}
To find it out we should compile it into an executable binary named a.out
first, then run it using valgrind:
$ valgrind ./a.out
==13982== Memcheck, a memory error detector
==13982== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==13982== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==13982== Command: ./a.out
==13982==
==13982==
==13982==
==13982== HEAP SUMMARY:
==13982== in use at exit: 12 bytes in 1 blocks
==13982== total heap usage: 1 allocs, 0 frees, 12 bytes allocated
==13982==
==13982== LEAK SUMMARY:
==13982== definitely lost: 12 bytes in 1 blocks
==13982== indirectly lost: 0 bytes in 0 blocks
==13982== possibly lost: 0 bytes in 0 blocks
==13982== still reachable: 0 bytes in 0 blocks
==13982== suppressed: 0 bytes in 0 blocks
==13982== Rerun with --leak-check=full to see details of leaked memory
==13982==
==13982== For counts of detected and suppressed errors, rerun with: -v
==13982== Use --track-origins=yes to see where uninitialised values come from
==13982== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
As you can see in LEAK SUMMARY
, valgrind find the leak. Drill down by adding --leak-check=full
parameter,
$ valgrind --leak-check=full ./a.out
...
==31324== HEAP SUMMARY:
==31324== in use at exit: 12 bytes in 1 blocks
==31324== total heap usage: 1 allocs, 0 frees, 12 bytes allocated
==31324==
==31324== 12 bytes in 1 blocks are definitely lost in loss record 1 of 1
==31324== at 0x4C294B9: operator new[](unsigned long) (vg_replace_malloc.c:348)
==31324== by 0x400688: main (in /data/home/mckelvin/tmp/a.out)
==31324==
==31324== LEAK SUMMARY:
==31324== definitely lost: 12 bytes in 1 blocks
==31324== indirectly lost: 0 bytes in 0 blocks
==31324== possibly lost: 0 bytes in 0 blocks
==31324== still reachable: 0 bytes in 0 blocks
==31324== suppressed: 0 bytes in 0 blocks
...
And now you find it.
==31324== 12 bytes in 1 blocks are definitely lost in loss record 1 of 1
==31324== at 0x4C294B9: operator new[](unsigned long) (vg_replace_malloc.c:348)
==31324== by 0x400688: main (in /data/home/mckelvin/tmp/a.out)
To find a memory leak in libmc, you should call the suspect code in an executable file first. Simply you can add it to tests/profile_client.cpp
and compile it:
mkdir -p build
cd build
cmake ..
make
valgrind ./tests/profile_client