cs205-lecture-examples

Example codes used during Harvard CS205 lectures
git clone https://git.0xfab.ch/cs205-lecture-examples.git
Log | Files | Refs | README | LICENSE

heap_stack.c (919B)


      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 
      4 int main(void)
      5 {
      6     // Allocated on stack when main function runs.  This is an example of
      7     // automatic memory allocation managed by the compiler using the stack.
      8     char on_stack[1 << 10]; // allocates 1024 bytes on the stack
      9 
     10     // Allocated on the heap at runtime.  This is an example of dynamic memory
     11     // allocation managed by the operating system at runtime (this memory
     12     // request involves the OS kernel)
     13     char *pointer = (char *)malloc(1 << 10); // allocates 1024 bytes on the heap
     14 
     15     // Compare the memory addresses of the two allocations
     16     // clang-format off
     17     printf("Address of variable `on_stack` (on stack):   %p\n", (void *)&on_stack);
     18     printf("Address of variable `pointer` (on stack):    %p\n", (void *)&pointer);
     19     printf("Address where `pointer` points to (on heap): %p\n", (void *)pointer);
     20     // clang-format on
     21 
     22     return 0;
     23 }