Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Array initialization segfaults depending on size and call to printf()

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 N to a value <= 590:
    This runs without errors, with or without output.
  • set N to 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?

like image 299
f4lco Avatar asked Feb 03 '26 08:02

f4lco


1 Answers

The amount of stack you have available to your app is very system dependent, and automatic variables (such as your double arrays) consume stack space. Calling a function requires additional stack space (for its variables, and housekeeping such as saved registers and a return point). You're going off the end of your stack and trying to access memory you're forbidden to access.

like image 175
mah Avatar answered Feb 05 '26 20:02

mah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!