1

As a personal project, I want to write my own malloc implementation in C using sbrk (not mmap). I know that I can use sbrk(0) to determine the end of the data segment, which would mark the end of my heap. However, I would like to accurately have my malloc return NULL instead of having my heap overflow into the stack. Is there a method I can use to determine where the stack ends to detect this sort of situation?

user129137
  • 71
  • 1
  • 4
  • Maybe you will find this useful. https://eli.thegreenplace.net/2011/02/04/where-the-top-of-the-stack-is-on-x86/ – Bwebb Dec 13 '18 at 23:22
  • 1
    Modern OS's use virtual memory management, which means that your notions of memory layout are obsolete. – user3386109 Dec 13 '18 at 23:41
  • @user3386109 Can you elaborate? I'm familiar with the concept of virtual memory, but I thought that the job of virtual memory was to support the abstraction that a process owns a single contiguous address space. Within the virtual address space, I figured that the user process would have to manage its own heap in virtual memory between the code and stack – user129137 Dec 14 '18 at 00:10
  • Virtual memory supports the abstraction that each process has its own address space. Hence there is no need to worry about address conflicts between processes. The notion of contiguous is problematic. On a 64-bit system with 64GB of physical memory and 256GB of swap space on disk, the total address space (2^64 bytes) is massive compared to the usable address space (~2^39 bytes). – user3386109 Dec 14 '18 at 00:25
  • Which means that keeping things (like stack and heap) contiguous is no longer a consideration. In fact, for [security reasons](https://en.wikipedia.org/wiki/Address_space_layout_randomization), things like the stack and heap are deliberately scrambled in memory. – user3386109 Dec 14 '18 at 00:25
  • @user3386109 I understand that the very large 64 bit address space wouldn't fit in memory, and that contiguous virtual addresses don't imply contiguous physical addresses (e.g. at the end of one virtual page and the start of another). However, I thought that a process would know nothing about physical memory addresses, and be free to arrange its stack heap and code in whatever way the compiler/assembly programmer decides, so typically with code and heap at the top of the virtual address space and stack at the bottom – user129137 Dec 14 '18 at 18:11

0 Answers0