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
没有发现任何内存泄漏!我是在错误地使用 valgrind
吗,还是这是一个 bug?
malloc
定义一个“同义词”。但仍不清楚它如何与静态链接的可执行文件一起使用。 - Eugene Sh.