Reputation: 1430
I would like to know why some of these programs are throwing a segfault while others aren't.
This program throws a segfault:
#include <stdio.h>
int main(){
int ar[2096263];
printf("asdf");
}
This one doesn't:
#include <stdio.h>
int main(){
int ar[2096263];
}
This program doesn't:
#include <stdio.h>
int main(){
int ar[2096262];
printf("asdf");
}
This one does:
#include <stdio.h>
int main(){
int ar[2096262];
printf("asdf");
printf("asdf");
printf("asdf");
printf("asdf");
printf("asdf");
}
this one doesn't:
#include <stdio.h>
int main(){
int ar[2096262];
printf("asdf");
printf("asdf");
printf("asdf");
printf("asdf");
}
I don't understand why calling printf changes the limit on the size of the array I can have in main. Also, Why can't I have more than 2096262 ints in an array?
Thanks
Upvotes: 1
Views: 74
Reputation: 34578
You have declare locally. Local array store in stack section of memory and size of the stack is limited.so, when you give size more than stack, you get segmentation fault. It's also called stack overflow problem.
To have larger arrays, you need to either declare it as a static variable or in file scope.
static int ar[2096263]; // This works fine.
Upvotes: 1
Reputation: 409136
Due to implementation reasons local variables, including arrays, are stored on the stack. Function calls also add to the stack, both with some meta-information but also with the called functions local variables. It all adds up.
Now, the stack is a limited resource, for example on Windows the default process stack size is only a single MB.
On Linux (which I assume you use since you mention "segmentation fault") the default stack size is 8MB, and with two million four-byte integers on the stack (sizeof(int)
is usually 4) you hit that limit and have a stack overflow.
Upvotes: 4