Search code examples
gdbheap-memory

How does GDB know where the heap is allocated


In GDB, running info proc mappings dumps the address space of the target, including the heap. My question is, how does GDB know where the heap is allocated? Obviously, something like malloc returns an address, but it does not specify the exact heap start address or its allocated size.


Solution

  • When debugging a live process on Linux, GDB's info proc mappings command parses the /proc/pid/maps file - which contains the details of a process's memory regions - then formats and displays the information. If the pathname field of an entry in the maps file says [heap], that's what GDB will display.

    The Linux kernel's implementation. of /proc/pid/maps will show [heap] on the line corresponding to the memory region that contains the address known as the break, which historically has been the top of the data segment. The break can be moved to higher or lower addresses by using the sbrk system call.

    glibc's malloc uses the heap for small allocations. For larger allocations, it calls mmap with anonymous backing, and you can see these memory regions in the maps file - they have no pathname field.

    I've written a small program which calls malloc to allocate memory in a variety of sizes, then displays the memory region where each allocation was placed. It's in my answer to Can't search into heap using gdb.