linux命令如下:valgrind --tool=memcheck --leak-check=full ./a.out
若没有valgrind工具,ubuntu下需要sudo apt-get install valgrind
如下:
举例说明:
1 #include <iostream> 2 using namespace std; 3 4 int main(int argc, char *argv[]) 5 { 6 string* s = new string("hello world"); 7 cout<<*s<<endl; 8 9 int* m = new int(100); 10 cout<<*m<<endl; 11 12 delete m; 13 14 return 0; 15 } 16 17 //running: 18 nol@nol-VirtualBox:~/desktop$ valgrind --tool=memcheck --leak-check=full ./a.out 19 ==5233== Memcheck, a memory error detector 20 ==5233== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al. 21 ==5233== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info 22 ==5233== Command: ./a.out 23 ==5233== 24 hello world 25 100 26 ==5233== 27 ==5233== HEAP SUMMARY: 28 ==5233== in use at exit: 72,736 bytes in 2 blocks 29 ==5233== total heap usage: 4 allocs, 2 frees, 73,764 bytes allocated 30 ==5233== 31 ==5233== 32 bytes in 1 blocks are definitely lost in loss record 1 of 2 32 ==5233== at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) 33 ==5233== by 0x400C40: main (in /home/nol/desktop/a.out) 34 ==5233== 35 ==5233== LEAK SUMMARY: 36 ==5233== definitely lost: 32 bytes in 1 blocks 37 ==5233== indirectly lost: 0 bytes in 0 blocks 38 ==5233== possibly lost: 0 bytes in 0 blocks 39 ==5233== still reachable: 72,704 bytes in 1 blocks 40 ==5233== suppressed: 0 bytes in 0 blocks 41 ==5233== Reachable blocks (those to which a pointer was found) are not shown. 42 ==5233== To see them, rerun with: --leak-check=full --show-leak-kinds=all 43 ==5233== 44 ==5233== For counts of detected and suppressed errors, rerun with: -v 45 ==5233== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0) 46 nol@nol-VirtualBox:~/desktop$