How is heap usually implemented?

Possible Duplicate:
How is heap and stack memories managed, implemented, allocated?

Hi, my question is about heap, not the data structure, but the area of memory that is used for dynamic memory allocation.

Suppose we're writing a program in C (or maybe C++) and somewhere in the depths of its code a call to malloc() is made (or operator new is invoked, in case of C++). Now what is the location of the allocated memory? Does the compiler (linker?) add a data segment that is used as a heap? How is the size of that segment determined? What will happen if we try to allocate a chunk of memory that is bigger than the entire "heap segment"? Will the heap be expanded? If yes, how?


The OS allocates pages, which it returns to malloc/free, which then break those pages up into blocks of the requested size, from memory. The OS can allocate any pages in the user's address space that aren't already requested. There is no heap segment. The allocated memory is in whatever location the OS determines.


There is a description of the inner workings of dlmalloc (the malloc() implementation used on glibc, uClibc and many other places) here.

Unix-like OSes have two main interfaces for requesting/releasing memory:

  • brk() expands/shrinks the data segment.
  • mmap()/munmap() request/release additional memory mappings.
  • The Windows API is actually malloc()/free() like, with function like HeapAlloc()/HeapFree().


    Old unix implementations used mechanism sbrk() --system request for moving last data section boundary. When memory is allocated, tuntime library calls system to move data boundary up, and use newly coming memory.

    New operational systems use virtual memory, so malloc requests new free VM pages from the system when necessary.

    Standalone applications (which run on bare hardware, microcontrollers etc.) have all allocated memory. Library know about all memory because linker script defines symbols for dynamic area. E. g. something like freemembot and freememtop , for lowest and highest free memory area location.

    链接地址: http://www.djcxy.com/p/80434.html

    上一篇: 在C ++中定制实现malloc

    下一篇: 通常如何实现堆?