Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 21994

Does every function get its own stack in c?

$
0
0

I recently learned about stacks, so I was experimenting to see what the stack size is and what happens when it overflows. I found out that on Unix the default stack size is 8 MiB, and that supports my findings since I cannot declare a string having size greater than or equal to 8 MiB in my main function. However, when I declare a variable in main() it affects other functions. For example:

#include <stdio.h>void foo(void){    long int size = 1024*1024*2;    char str[size];    str[size - 1] = 'a';    printf("%c\n", str[size - 1]);}int main(int argc, char** argv){    long int size = 1024*1024*6;    char str[size];    str[size - 1] = 'a';    printf("%c\n", str[size - 1]);    foo();    return 0;}

This code results in segmentation fault but if I make the string size 5 MiB in main() then there is no segmentation fault. Does that mean my C program cannot allocate more than 8 MiB of RAM for local variables (of all functions)? If so, what IS the point of stacks?


Viewing all articles
Browse latest Browse all 21994

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>