Skip to content

Instantly share code, notes, and snippets.

@ishankhare07
Last active April 1, 2018 08:50
Show Gist options
  • Save ishankhare07/bed3b00f517796715f734635a2992522 to your computer and use it in GitHub Desktop.
Save ishankhare07/bed3b00f517796715f734635a2992522 to your computer and use it in GitHub Desktop.
A C program showing the structure of address spaces
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("location of Code: %p\n", (void *) main);
printf("location of Heap: %p\n", malloc(1));
int x = 10;
printf("location of Stack: %p\n", &x);
return 0;
}

The following depicts the structure of a typical address space

  +-------------------------------------+
  |             Program Code            |
  +-------------------------------------+
  |                 Heap                |   Grown downwards
  +-------------------------------------+   vvvvvvvvvvvvvvv
  |                  ^                  |
  |                  |                  |
  |                  |                  |
  |                  |                  |
  |                  |                  |
  |                  |                  |
  |              Free Space             |
  |                  |                  |
  |                  |                  |
  |                  |                  |
  |                  |                  |
  |                  v                  |
  +-------------------------------------+   ^^^^^^^^^^^^^
  |                Stack                |   Grows upwards
  +-------------------------------------+

The output of the program is

location of code: 0x400517
location of heap: 0x19fd420
location of stack: 0x7ffdb3390134

Which is consistent with the order of these locations as depicted in the diagram

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment