[Linux] How to check if program has memory leaks
You can check your program using command:
valgrind your_program |
Example of usage:
We have following C++ program (tst.cpp):
int main() { int * tab = new int[1000000]; return 0; } |
Obviously it generates memory leak. We compile it to tst file and execute:
valgrind tst |
==20777== Memcheck, a memory error detector. ==20777== Copyright (C) 2002-2008, and GNU GPL'd, by Julian Seward et al. ==20777== Using LibVEX rev 1884, a library for dynamic binary translation. ==20777== Copyright (C) 2004-2008, and GNU GPL'd, by OpenWorks LLP. ==20777== Using valgrind-3.4.1-Debian, a dynamic binary instrumentation framework. ==20777== Copyright (C) 2000-2008, and GNU GPL'd, by Julian Seward et al. ==20777== For more details, rerun with: -v ==20777== ==20777== ==20777== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 17 from 1) ==20777== malloc/free: in use at exit: 4,000,000 bytes in 1 blocks. ==20777== malloc/free: 1 allocs, 0 frees, 4,000,000 bytes allocated. ==20777== For counts of detected errors, rerun with: -v ==20777== searching for pointers to 1 not-freed blocks. ==20777== checked 93,180 bytes. ==20777== ==20777== LEAK SUMMARY: ==20777== definitely lost: 0 bytes in 0 blocks. ==20777== possibly lost: 4,000,000 bytes in 1 blocks. ==20777== still reachable: 0 bytes in 0 blocks. ==20777== suppressed: 0 bytes in 0 blocks. ==20777== Rerun with --leak-check=full to see details of leaked memory.
One thought on “[Linux] How to check if program has memory leaks”
Hi, cool post. I have been pondering this topic,so thanks for writing. I’ll probably be coming back to your blog. Keep up great writing