2

I am a beginner to C++. I am trying to read in input from the console, so I have the code below:

#include <iostream>
#include <string.h>
#include <string>

using namespace std;
#define maxn 2006
int A[maxn][maxn];

int main() {

    memset(A,0,sizeof(A));
    int n = 0,m = 0;
    cin >> n >> m;
    for(int i = 0; i < n; ++i){
        string str; cin >> str;
        for(int j =0; j < m; ++j)
            A[i][j] = str[j]-'0';
    }
    return 0;
}

A sample input looks like this

5 7  
0101010
1000101
0101010
1010101
0101010

My program above works perfectly.

However, for learning purpose, I did nothing but move the declaration of 2D int array A into the main function, which looks like this:

#include <iostream>
#include <string.h>
#include <string>

using namespace std;
#define maxn 2006

int main() {
    int A[maxn][maxn];
    memset(A,0,sizeof(A));
    int n = 0,m = 0;
    cin >> n >> m;
    for(int i = 0; i < n; ++i){
        string str; cin >> str;
        for(int j =0; j < m; ++j)
            A[i][j] = str[j]-'0';
    }
    return 0;
}

I rebuild it and run, I get segmentation fault 11.

Anyone know what's going on here? Why does the code break down after the subtle change?

Thanks!

shin
  • 671
  • 6
  • 10
  • Possible duplicate of [Definitive List of Common Reasons for Segmentation Faults](https://stackoverflow.com/questions/33047452/definitive-list-of-common-reasons-for-segmentation-faults) – Barmar Jan 04 '18 at 04:11
  • 1
    See the section of that duplicate question with the heading **Stack Overflow** – Barmar Jan 04 '18 at 04:11
  • *However, for learning purpose,* -- The real lesson learned is to use dynamically allocated memory, preferably `std::vector`. Doing that, and you will not run into this problem of stack overflow (as the answers given have stated). – PaulMcKenzie Jan 04 '18 at 04:14
  • File scope variables have static storage duration; to retain this behaviour in the function use `static int A[maxn][maxn];` – M.M Jan 04 '18 at 04:42

1 Answers1

4

Anyone know what's going on here?

Yes: stack overflow.

By moving the variable you made it a local (stack allocated) instead of global (allocated at startup in the BSS section of the binary).

The size of your variable is 16,096,144 bytes (2006 * 2006 * 4). And stack is usually limited, often to 8MB. On a UNIX system, after ulimit -s unlimited, your modified program may start working again.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362