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

stackoverflow.c (947B)


      1 #include <stdio.h>
      2 
      3 int main(void)
      4 {
      5     // On Linux system the size of the stack can be checked (and configured)
      6     // with
      7     //     ulimit -s
      8     //  On my system the stack size is 8192kB (8MB).  If your program allocates
      9     //  more than 8MB on the stack your application will fail with a
     10     //  segmentation fault.  The stack is used for automatic memory allocation
     11     //  when functions execute and should not be used for simulation data for
     12     //  example.  Such large data must always be allocated on the heap.  If you
     13     //  have a very deep recursion in your code that calls many function which
     14     //  all in total require more than 8MB (on my system) you will also run into
     15     //  a stack overflow.
     16 
     17     // The following code is buggy and will crash due to stack overflow
     18     char large_memory[8 * (1 << 20)]; // 8MB of memory on stack
     19     printf("Memory access will fail: %d\n", large_memory[0]); // segfault
     20 
     21     return 0;
     22 }