3

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?

f4lco
  • 3,728
  • 5
  • 28
  • 53
  • 2
    Well, that's approximatively 2 MB of stack storage... That's huge ! Please see this : http://stackoverflow.com/questions/1825964/c-c-maximum-stack-size-of-program – SirDarius Jun 11 '12 at 15:30
  • 2
    @user1417475 Segmentation? 64k segments? In which decade do you live? – glglgl Jun 11 '12 at 15:30
  • @user1417475: Any document about assembly language programming that's more than a few years old is probably more harmful than helpful... – R.. GitHub STOP HELPING ICE Jun 11 '12 at 15:41

3 Answers3

2

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.

mah
  • 39,056
  • 9
  • 76
  • 93
1

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, calloc or realloc. Don't forget to free this memory by calling free when 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

Community
  • 1
  • 1
LihO
  • 41,190
  • 11
  • 99
  • 167
0

You're getting a stack overflow. However I can reproduce it here both with and without the printf with VC++. My best guess is that the operation of pushing arguments to the printf on the stack causes the error to manifest itself. Does it still happen if you call a function that takes no paramters?

James
  • 9,064
  • 3
  • 31
  • 49
  • You're right about pushing arguments on stack. If I introduce a new function without parameters the error doesn't appear. – f4lco Jun 11 '12 at 15:44