Another student asked me what could be wrong with his C code. I successfully reproduced the erroneous behavior and have completely no idea why this segfaults. Consider this tiny C programm:
#include <stdio.h>
int main(void) {
int N = 590;
double A[N][N];
double B[N][N];
double C[N][N];
printf("done");
}
- Set
Nto a value <= 590:
This runs without errors, with or without output. - set
Nto a value > 590:- Runs flawlessy with output line removed.
- Compile and run with output: segmentation fault
What’s the reason for this? Can anybody explain?
You try to allocate more memory than it’s available on the stack which causes stack overflow. Usually it is much better to allocate huge arrays like that dynamically by using
malloc,callocorrealloc. Don’t forget to free this memory by callingfreewhen you finish with it 🙂These questions will help you too:
C/C++ maximum stack size of program
Segmentation Fault on creating an array in C
Segmentation Fault When Using Variable To Initiate Array