When allocating a int
as well as a large array on the stack in C, the program executes without error. If I however, initialize the variable on the stack beforehand, it crashes with a segfault (probably because the stack size was exceeded by the large array). If initializing the variable after declaring the array this would make sense to me.
What causes this behavior, memory wise?
I was under the impression, that by simply declaring a variable on the stack, the needed space would be allocated, leading to an immediate crash when allocating very large datatypes.
My suspicion is that it has something to do with the compiler optimizing it away, but it does not make sense, considering I am not changing foo
in the second example either.
I am using gcc 7.2.0 to compile, without any flags set. Executed on Ubuntu 17.10.
This runs without errors:
int main(){
int i;
unsigned char foo [1024*1024*1024];
return 0;
}
while this crashes immediately:
int main(){
int i = 0;
unsigned char foo [1024*1024*1024];
return 0;
}
Can somebody give me some insight what is happening here?