工具
valgrind
优点:
- 无需修改自己的代码
- 能够定位到具体产生内存泄露的函数调用堆栈和代码行号
安装valgrind
sudo apt install valgrind
编译你的程序,增加-g编译选项
假设我们的测试代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdint.h>
#include <pthread.h>
void* my_malloc(size_t __size)
{
return malloc(__size);
}
void* thread_handle(void* arg)
{
char* p = NULL;
p = my_malloc(1);
return arg;
}
int main()
{
pthread_t thread;
pthread_create(&thread, NULL, thread_handle, NULL);
pthread_join(thread, NULL);
char* p2 = my_malloc(4);
memset(p2, 0, 4);
return 0;
}
编译:
gcc valgrind_test.c -o test -g -lpthread
使用valgrind 进行检测
前面的命令行都是一些参数,最后跟自己的程序
valgrind --tool=memcheck --leak-check=full --show-reachable=yes --trace-children=yes ./test
输出样例
==1287== Memcheck, a memory error detector
==1287== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==1287== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==1287== Command: ./test
==1287==
==1287==
==1287== HEAP SUMMARY:
==1287== in use at exit: 5 bytes in 2 blocks
==1287== total heap usage: 3 allocs, 1 frees, 277 bytes allocated
==1287==
==1287== 1 bytes in 1 blocks are definitely lost in loss record 1 of 2
==1287== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==1287== by 0x40075D: my_malloc (valgrind_test.c:10)
==1287== by 0x40077D: thread_handle (valgrind_test.c:16)
==1287== by 0x4E416B9: start_thread (pthread_create.c:333)
==1287==
==1287== 4 bytes in 1 blocks are definitely lost in loss record 2 of 2
==1287== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==1287== by 0x40075D: my_malloc (valgrind_test.c:10)
==1287== by 0x4007D4: main (valgrind_test.c:28)
==1287==
==1287== LEAK SUMMARY:
==1287== definitely lost: 5 bytes in 2 blocks
==1287== indirectly lost: 0 bytes in 0 blocks
==1287== possibly lost: 0 bytes in 0 blocks
==1287== still reachable: 0 bytes in 0 blocks
==1287== suppressed: 0 bytes in 0 blocks
==1287==
==1287== For counts of detected and suppressed errors, rerun with: -v
==1287== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
从上面可以看出有两处内存泄露。
第一处:
thread_handle (valgrind_test.c:16) -> my_malloc (valgrind_test.c:10) -> malloc
第二处:
main (valgrind_test.c:28) -> my_malloc (valgrind_test.c:10) -> malloc