// This program allocates some Stack and Heap variables
// and prints their memory addresses so you can see that
// the addresses are in different ranges. Likewise, the
// code is in yet another address range.
//
// gcc Heap.c -o /tmp/Heap
// /tmp/Heap
//

#include <stdio.h>
#include <stdlib.h>

#define ABC "abc"

static int sum(int a, int b) {
  printf("==== Function parameters go on the stack\n");
  printf("param a(%d) is at %p\n", a, &a);
  printf("param b(%d) is at %p\n", b, &b);
  return a+b;
}

int main(int argc, char *argv[]) {
  int stack0 = 30;	// Arbitrary stack variables
  int stack1 = 40;

  printf("==== Local variables go on the stack\n");
  printf("stack0(%d) is at %p\n", stack0, &stack0);
  printf("stack1(%d) is at %p\n\n", stack1, &stack1);

  sum(10, 20);

  void *heap[2];	// Heap pointers
  int i;
  printf("\n==== Allocated Memory goes on the heap\n");
  for (i = 0; i < 2; i++) {
    heap[i] = malloc(10);
    printf("heap[%d] points to %p\n", i, heap[i]);
  }

  printf("\n==== Constants go in static memory\n");
  printf("const(%s) is at %p\n", ABC, &ABC);

  printf("\n==== Code goes in static memory\n");
  printf("sum() is at %p\n", &sum);
  printf("main() is at %p\n", &main);
  
  return 0;
}

/* Output on Windows Bash:
      ==== Local variables go on the stack
      stack0(30) is at 0x7fffec8b1684
      stack1(40) is at 0x7fffec8b1688

      ==== Function parameters go on the stack
      param a(10) is at 0x7fffec8b165c
      param b(20) is at 0x7fffec8b1658

      ==== Allocated Memory goes on the heap
      heap[0] points to 0x7fffe50452b0
      heap[1] points to 0x7fffe50452d0

      ==== Constants go in static memory
      const(abc) is at 0x7f5328f33114

      ==== Code goes in static memory
      sum() is at 0x7f5328f321a9
      main() is at 0x7f5328f32205
*/

/* Output on fox machines:
      ==== Local variables go on the stack
      stack0(30) is at 0x7ffde3915a74
      stack1(40) is at 0x7ffde3915a78

      ==== Function parameters go on the stack
      param a(10) is at 0x7ffde3915a4c
      param b(20) is at 0x7ffde3915a48

      ==== Allocated Memory goes on the heap
      heap[0] points to 0x18cf010
      heap[1] points to 0x18cf030

      ==== Constants go in static memory
      const(abc) is at 0x4008c4

      ==== Code goes in static memory
      sum() is at 0x4005bd
      main() is at 0x40060f
*/
