可以使用Valgrind来诊断内存泄漏并提供详细报告。另外,可以使用LeakSanitizer来检测和定位内存泄漏。
示例代码:
#include
void func() { char* p = (char*) malloc(10); }
int main() { func(); return 0; }
编译时指定LeakSanitizer:
gcc -fsanitize=leak example.c
运行程序并查看LeakSanitizer报告:
./a.out ... # output from your program LeakSanitizer: detected memory leaks
Direct leak of 10 byte(s) in 1 object(s) allocated from: #0 0x7f81d06dbc00 in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.3+0xc5c00) #1 0x400601 in func /home/user/example.c:4 #2 0x400610 in main /home/user/example.c:9 #3 0x7f81cfa76b96 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21b96)
SUMMARY: AddressSanitizer: 10 byte(s) leaked in 1 allocation(s).
LeakSanitizer在程序运行时会实时检测内存泄漏,并在程序结束后提供详细的报告,包括泄漏的大小、泄漏的位置等。