0

I am running QEMU on a Ubuntu 20.04.2 machine, and have a GDB debugger attached to it.

I breaked at a line which does g_malloc. The return address does not belong to the heap memory region, where the virtual memory addresses are found via cat /proc/$PID/maps. I did a visual match of the return address against the output of maps, and found it in a data segment. This does not always happen - on some occasions, the return address is indeed found in the heap region.

  1. I have read that "The addresses returned by malloc and related functions come from whatever area your run-time environment uses for dynamic memory." Does this mean that g_malloc and malloc in general do not necessarily allocate memory in the heap region? I tried to search if this was true but what I found was that every search result says that it is only returning addresses in the heap.

  2. I have also read that "heap is actually part of the data segment of the executable itself". Again, I tried to search for an explanation about this statement, but found that others just said not to mix the heap and data segments together - and to see them being disparate.

  3. I am unable to reconcile my above 2 readings with my findings.

Brian Lee
  • 85
  • 1
  • 1
  • 7
  • On Ubuntu, `malloc` is implemented (usually) in [GNU glibc](https://www.gnu.org/software/glibc/) which is [free software](https://www.gnu.org/philosophy/free-sw.en.html). **You are allowed to download and study the source code of GNU libc**. In practice, `malloc` will try to reuse previously `free`d memory zones, and uses [mmap(2)](https://man7.org/linux/man-pages/man2/mmap.2.html) or [sbrk(2)](https://man7.org/linux/man-pages/man2/sbrk.2.html) when it cannot – Basile Starynkevitch Apr 20 '21 at 04:39
  • You can redefine your own `malloc`+`calloc`+`free` routines, or use other libraries like [musl](https://musl.libc.org/) or [jemalloc](http://jemalloc.net/) - both are open source, and **you are allowed to download and study their source code**. – Basile Starynkevitch Apr 20 '21 at 04:42
  • See [my favorite joke implementation of `malloc`](https://stackoverflow.com/a/8460584/841108). It is compliant with the [n1570](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf) C standard and very fast – Basile Starynkevitch Apr 20 '21 at 04:46
  • With [pthreads(7)](https://man7.org/linux/man-pages/man7/pthreads.7.html) there is no more a *single* data segment per [process](https://en.wikipedia.org/wiki/Process_(computing)). Check by using [pmap(1)](https://man7.org/linux/man-pages/man1/pmap.1.html) - e.g. on most [Qt](https://qt.io) or [GTK](https://gtk.org/) applications – Basile Starynkevitch Apr 20 '21 at 04:49

0 Answers0