2

Possible Duplicate:
Segmentation fault on large array sizes

A segmentation fault occurs when I run the program.

#include<iostream>
using namespace std;

int main(){
    int x[2000][2000];
    int y;
    cin >> y;
}

However, the following two programs are OK, when I run them.

#include<iostream>
using namespace std;

int x[2000][2000];
int main(){

    int y;
    cin >> y;
}

and

#include<iostream>
using namespace std;

int main(){
    int x[2000][2000];
    int y;
}

I am quite confused. Can anyone tell me why?

Community
  • 1
  • 1
ZHOU
  • 1,151
  • 2
  • 12
  • 27

2 Answers2

9

Congratulations, you've found a stack overflow.

In the first example, the large array x pushes y past the end of the stack, so accessing it crashes the program. (2) doesn't crash because the large array you declared is in the data segment and so not on the stack; (3) doesn't crash because you're not actually accessing memory past the end of the stack (you've declared it, but aren't reading or writing it).

ecatmur
  • 152,476
  • 27
  • 293
  • 366
2

In your first example, you are attempting to allocate 20,000*20,000*4 bytes (assuming 32-bit integers) on the stack. This amount to about 16MB of data, which is more than the stack size allocated for you by the compiler (typically about 1MB), so you run out of (stack) memory

In the second example, the compiler allocates the memory for x in a separate global space (not on the stack), which has enough space to hold it.

The third example is trickier, because it should seemingly result in the same situation as the first, but it is possible that your compiler optimized out the function as it deemed that no meaningful work is being done in that function (so no memory allocation for the local variables)

Attila
  • 28,265
  • 3
  • 46
  • 55