我写了这个小malloc
:
#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
来检查内存泄漏。您正在使用sbrk
在较低级别分配内存。 Valgrind不会查看这些功能,因此不会检测到泄漏。