1

I need to use two-dimensional table of boolean that helps me resolve problem with dynamic-programming method. Unfortunately I encountered an issue, where I want to print counted results. I didn't code much with c++ before so I don't understand what's wrong with this code, especially since I'm not using here any custom made structs, classes or pointers and I double checked if array bounds in iterators are correct.

Here's the simple code that's an example of my issue :

const short int N=1001;
const short int M=10001;

int main() {
    bool tab[N][M];
    for (int i=0;i<N;i++)
        for (int j=0;j<M;j++)
            tab[i][j]=false;

    int foo=0;
    for (int i=0;i<N;i++)
        for (int j=0;j<M;j++)
            if (!tab[i][j])
                foo++;

    cout << foo << endl;

    return 0;
}

Why trying to print foo value gets segmentation fault error? That variable is initialised before I try increasing it in the for function. When I remove the cout line everything is ok and program does finish the work (though I can't then see the results). Thanks in advance for helping me to solve this (most likely) simple issue.

John Dibling
  • 99,718
  • 31
  • 186
  • 324
tg_91
  • 43
  • 1
  • 3
  • 3
    Why did you omit the braces? – toasted_flakes Nov 11 '13 at 16:53
  • You must be getting int overflow. Change foo to unsigned long long int – Abhishek Bansal Nov 11 '13 at 16:56
  • 7
    Most likely a stack overflow - the array takes up (at least) 10MB, which might be too big for the stack. If that's the case, then dynamic allocation is the simplest solution. – Mike Seymour Nov 11 '13 at 16:57
  • 1
    int overflow would cause the value to wrap, so you'd get nonsensical outputs. Stack overflow seems more promising. Try lowering M and N – Oliver Matthews Nov 11 '13 at 16:59
  • This is not an undefined value overflow issue. It is a stack overflow. The activation record for `main()` requires 9.55MB of space, far more than any default runtime provides that I've ever seen. There are *dozens* of duplicate questions on SO, [such as this one](http://stackoverflow.com/questions/571945/getting-a-stack-overflow-exception-when-declaring-a-large-array). And you don't need *either* loop to reproduce this. – WhozCraig Nov 11 '13 at 17:43

1 Answers1

2

There is a segmentation fault error because you are trying to store a number too big for an integer variable.

You are trying to store 10011001 (1001 * 10001) in an integer variable when the maximum value it can store is 32767 (http://www.cplusplus.com/reference/climits/)

alex
  • 161
  • 1
  • 7
  • Integer overflow won't cause a segmentation fault - that's caused by accessing invalid memory. Also, `int` is 32 bits on most modern platforms, although you're right that there's no guarantee that it's larger than 16. – Mike Seymour Nov 11 '13 at 22:18