推荐使用工具valgrind
,安装:
sudo apt install valgrind #debian/ubuntu
内存泄漏示例代码如下:
/* code with memory leak */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *ptr = (int*)malloc(10);
return 0;
}
进行检测:
-> # valgrind --leak-check=full ./test
==14896== Memcheck, a memory error detector
==14896== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==14896== Using Valgrind-3.12.0.SVN and LibVEX; rerun with -h for copyright info
==14896== Command: ./test
==14896==
==14896==
==14896== HEAP SUMMARY:
==14896== in use at exit: 10 bytes in 1 blocks
==14896== total heap usage: 2 allocs, 1 frees, 72,714 bytes allocated
==14896==
==14896== 10 bytes in 1 blocks are definitely lost in loss record 1 of 1
==14896== at 0x4C2BBAF: malloc (vg_replace_malloc.c:299)
==14896== by 0x4004F3: main (test.cpp:6)
==14896==
==14896== LEAK SUMMARY:
==14896== definitely lost: 10 bytes in 1 blocks
==14896== indirectly lost: 0 bytes in 0 blocks
==14896== possibly lost: 0 bytes in 0 blocks
==14896== still reachable: 0 bytes in 0 blocks
==14896== suppressed: 0 bytes in 0 blocks
==14896==
==14896== For counts of detected and suppressed errors, rerun with: -v
==14896== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
windows上的话推荐使用CRT:Find memory leaks with the CRT library
参考:How to deallocate memory without using free() in C?
另外一个推荐使用的工具是AddressSanitizer,
使用方法参考博客:LeetCode 报错解决 heap-buffer-overflow Heap-use-after-free Stack-buffer-overflow Global-buffer-overflow
示例代码:
class A {
int a;
};
class B : public A {
int b;
};
int main() {
A *a = new B();
delete a;
return 0;
}
上面的代码会造成内存泄漏:
-> % g++ -fsanitize=address test.cpp
-> % ./a.out
=================================================================
==25445==ERROR: AddressSanitizer: new-delete-type-mismatch on 0x602000000010 in thread T0:
object passed to delete has wrong type:
size of the allocated type: 8 bytes;
size of the deallocated type: 4 bytes.
#0 0x7f901bc429d8 in operator delete(void*, unsigned long) (/usr/lib/x86_64-linux-gnu/libasan.so.4+0xe19d8)
#1 0x562ecf25d92c in main (/home/ubuntu/a.out+0x92c)
#2 0x7f901b791b96 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21b96)
#3 0x562ecf25d7a9 in _start (/home/ubuntu/a.out+0x7a9)
0x602000000010 is located 0 bytes inside of 8-byte region [0x602000000010,0x602000000018)
allocated by thread T0 here:
#0 0x7f901bc41458 in operator new(unsigned long) (/usr/lib/x86_64-linux-gnu/libasan.so.4+0xe0458)
#1 0x562ecf25d89b in main (/home/ubuntu/a.out+0x89b)
#2 0x7f901b791b96 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21b96)
SUMMARY: AddressSanitizer: new-delete-type-mismatch (/usr/lib/x86_64-linux-gnu/libasan.so.4+0xe19d8) in operator delete(void*, unsigned long)
==25445==HINT: if you don't care about these errors you may set ASAN_OPTIONS=new_delete_type_mismatch=0
==25445==ABORTING
报错中说明是new-delete-type-mismatch
,分配了8字节,结果只删除了4字节,明显的内存泄漏。