我写了这个malloc
的小版本(没有free
):
#include <cstdio>
#include <cstddef>
#include <unistd.h>
#define word_size sizeof(intptr_t)
#define align(n) ((n + word_size - 1) & ~(word_size - 1))
void* my_malloc(size_t size) {
void* p = sbrk(0);
printf("before allocation: %p\n", p);
if (sbrk(align(size)) == (void*) -1) {
// failed to allocate memory
return NULL;
}
printf("after allocation: %p\n", sbrk(0));
return p;
}
int main() {
int* foo = (int*) my_malloc(1);
*foo = 100;
printf("after allocation outside: %p\n", sbrk(0));
}
这是代码的输出:
before allocation: 0x1796000
after allocation: 0x1796008
after allocation outside: 0x1796008
如您所见,my_malloc
分配的内存尚未释放。但是,当我使用valgrind
通过以下命令运行它时:
valgrind --leak-check=yes ./main
我明白了:
==1592== Memcheck, a memory error detector
==1592== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==1592== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==1592== Command: ./main
==1592== HEAP SUMMARY:
==1592== in use at exit: 0 bytes in 0 blocks
==1592== total heap usage: 2 allocs, 2 frees, 73,728 bytes allocated
==1592==
==1592== All heap blocks were freed -- no leaks are possible
==1592==
==1592== For counts of detected and suppressed errors, rerun with: -v
==1592== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
如您所见,valgrind
找不到any内存泄漏!我是错误地使用了valgrind
,还是这是一个错误?
Valgrind通过链接其自身的功能代替malloc
,calloc
,realloc
和free
来检查内存泄漏。当valgrind报告内存泄漏时,您可以看到此信息:
==24877== 8 bytes in 1 blocks are definitely lost in loss record 1 of 1
==24877== at 0x4C29EA3: malloc (vg_replace_malloc.c:309)
==24877== by 0x4EC3AA9: strdup (in /usr/lib64/libc-2.17.so)
==24877== by 0x40058E: main (x1.c:9)
您可以在这里看到strdup
的libc版本被调用,但是[lib] malloc
的valgrind替换被调用,而不是libc malloc
。
您正在使用sbrk
在较低级别分配内存。 Valgrind不会拦截该功能,因此不会检测到泄漏。实际上,根据valgrind documentation,它将sbrk
列为依赖项。从第1.1.4节开始:
要找出Valgrind使用了哪些glibc符号,请恢复链接标志
-nostdlib -Wl,-no-undefined
。这会导致链接失败,但会告诉您您所依赖的。我大部分但不是全部摆脱了glibc依赖关系;剩下的是,IMO,相当无害。 AFAIK当前的依存关系是:memset
,memcmp
,stat
,system
,sbrk
,setjmp
和longjmp
。