Mmap and valgrind, mmap doesnt increase heap size

99封情书 提交于 2021-02-07 20:28:34

问题


I'm attending operating systems course on my university, one of the tasks we were given is to implement simple malloc using mmap. Now that i got it working i tried to use valgrind to detect any bugs left. And regarldess of freeing memory or not, valgrind doesnt see any memory leaks. As an example consider following C code:

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;
}

lets compile it with gcc, and use valgrind. Here is what valgrind returns:

==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)

This is something unexpected, we'd normally want pages to be unmapped before exitting program to see such message.

At first i thought that pages might be mapped lazily, this is why i forced performing doing some stuff on that page like changing values, and printing them, but as we can see this is not issue.

This is probably something wrong with valgrind or my understanding of how mmap and valgrind works.


回答1:


mmap doesn't increase heap size

The heap is separate from memory obtained from mmap. There are 2 basic ways a Unix process obtains memory:

  • by increasing the "break" via brk(2)/sbrk(2) - this is the heap
  • by mapping in memory using mmap - these are independent from the heap

Anatomy of a Program in Memory has a good picture:

Anatomy of a Program in Memory

This is probably something wrong with valgrind or my understanding of how mmap and valgrind works.

Reading the memcheck manual might help, especially the section on custom allocators. The gist of it is that for the purposes of leak checks mmap-allocated chunks are invisible to valgrind. It intercepts only malloc, calloc, free, new etc.


Confusingly some mmap-allocated areas are tracked by valgrind! This happens for example when malloc chooses to mmap memory in rather than using the heap.



来源:https://stackoverflow.com/questions/28251833/mmap-and-valgrind-mmap-doesnt-increase-heap-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!