3

The following image shows where the sections of a process are laid out in the process's virtual address space:

enter image description here

You can see that there is only one stack section (since this process only has one thread I assume).

But what if this process has another thread, where will the stack for this second thread be located? will it be located immediately below the first stack?

  • Such memory layout might be used for programming an embedded processor without any OS, but is avoided on security-conscious modern systems with memory protection. Importantly, stacks are fixed sized, e.g. my system uses 8MB stacks (though not all of that may be mapped into virtual memory immediately). The stacks are still typically placed near the top of the virtual memory space. The pthread_create manpage for Linux happens to contain an example that prints out stack locations for multiple threads. – amon Jul 1 '17 at 13:59
2

That's a pretty old and mostly obsolete model for virtual memory layout.

In reality instructions and global each start at some separate random location. Linked libraries are mapped separately from the main program to their own random locations.

The heap is created by asking for blank pages as needed. These may or may not be contiguous to previously returned pages of memory.

The first and last chunk of virtual memory is often reserved and marked non-accessible to catch null pointer related bugs.

Even after all that there will be enough free space to reserve space (again in random locations) for the stack of each thread created.

  • "In reality instructions and global each start at some separate random location" Do you mean random location as in the text section can be located above the data section, or do you mean that the order is maintained but instead of the data section starting at address 1000, it can start at address 1017? – joseph_m Jun 30 '17 at 13:34
  • Yeah they can be reordered. Along with leaving some unused space between them (that can later be claimed by the heap or new lib that gets mapped in) – ratchet freak Jun 30 '17 at 13:37
  • And 64 bit systems usually don't touch the first 4GB at all to avoid some classes of bugs. – gnasher729 Jul 1 '17 at 16:09
  • @gnasher729 That seems interesting. Could you elaborate on that? What systems, what bugs? – Deduplicator Jul 1 '17 at 18:21
  • 1
    @Deduplicator mistaken conversion from pointer to a int which would slice off the high bits. when converted back to pointer it'll be in the lower 4 gigs, dereferencing that will lead to a segfault. – ratchet freak Jul 1 '17 at 19:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.