【发布时间】:2015-01-31 12:57:18
【问题描述】:
我正在我的大学学习操作系统课程,我们的任务之一是使用 mmap 实现简单的 malloc。现在我让它工作了,我尝试使用 valgrind 来检测任何遗留的错误。不管是否释放内存,valgrind 都没有看到任何内存泄漏。例如,考虑以下 C 代码:
int main()
{
int psize = getpagesize(),i;
int *ptr = mmap(NULL, psize, PROT_WRITE | PROT_READ, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
for(i = 0; i < psize/4; i++) ptr[i] = i;
for(i = 0; i < psize/4; i++) printf("%d\n", ptr[i]);
return 0;
}
让我们用 gcc 编译它,并使用 valgrind。以下是 valgrind 返回的内容:
==17841== Memcheck, a memory error detector
==17841== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==17841== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==17841== Command: ./test
==17841==
------------ printing numbers from 0 to 1023
==17841==
==17841== HEAP SUMMARY:
==17841== in use at exit: 0 bytes in 0 blocks
==17841== total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==17841==
==17841== All heap blocks were freed -- no leaks are possible
==17841==
==17841== For counts of detected and suppressed errors, rerun with: -v
==17841== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
这是出乎意料的,我们通常希望在退出程序之前取消映射页面以查看此类消息。
起初我认为页面可能被延迟映射,这就是为什么我强制在该页面上执行一些操作,例如更改值并打印它们,但我们可以看到这不是问题。
这可能是 valgrind 或我对 mmap 和 valgrind 工作原理的理解有问题。
【问题讨论】:
-
valgrind与系统malloc相关(或提供自己的)。我不确定它是否可以使用您自己的malloc,除非您在您的malloc实现中提供特定的钩子!
标签: c linux valgrind paging mmap