0
int main(int argc, const char * argv[]) {
    int N,M;
    std::cin >> N;
    std::cin >> M;
    bool member[N];
    for (int i= 0; i < N ; i++) {
        member[i] = false;
    }
    int test[M][N];
    int testSize[M];
    /*//std::fill_n(testSize, M, 0);
    for (int i = 0; i < M; i++) {
        std::fill_n(test[M], N, -1);
    }*/
    for (int i = 0; i < M; i++) {
        for (int j = 0; j < N ; j++) {
            test[i][j] = -1;
        }
        testSize[i] = 0;
    }
}

This is my c++ code above, that is simple code, isn't it?

But When the program got M as 100000 and N as 1000, there is EXC_BAD_ACCESS at second for loop.

I do not know why it is happening.

When smalle size data is put into, there is no error, but This case made it an error.

I'm solving an algorithm problem and confronting unknowing error.

Is there any point to fix at my program?

As you see my code, what I want is to initialize the array test and testSize to the same value; -1 and 0.

dragosht
  • 3,237
  • 2
  • 23
  • 32
LKM
  • 2,410
  • 9
  • 28
  • 53

1 Answers1

-1

int test[M][N]; allocates an array of M*N elements on the stack. When M == 100000 and N==1000 it is an array of 100 million elements. int is usually at least 4 bytes, so you are trying to allocate 400MB array on a stack, which won't fit with default (or probably any at all) linker settings.

What you can do is to allocate that much memory on heap using malloc or new[]. You can also use 3rd-party classes for operating matrices that will do it for you.

Paul
  • 13,042
  • 3
  • 41
  • 59
  • Should I think another, more efficient way to store that data? Is there any solution ? I first have the problem like this – LKM Nov 09 '15 at 16:37
  • Wait, there's more to it! The main problem is that the size of the array isn't known at compile time, so even with M=10 and N=2 it won't work. Then again, what you say isn't wrong, but you are overlooking the other problem. – Fabio says Reinstate Monica Nov 09 '15 at 16:41
  • @FabioTurati Variable length array is a C99 feature, compiler might support it even in C++ mode and it might work. – Paul Nov 09 '15 at 16:44
  • @FabioTurati I already did test the case N=100,M=3090 but I appreciate what you said, can I ask what you actually mean that 'the size of the array isn't known at compile time'? – LKM Nov 09 '15 at 16:45
  • 2
    @LKM In C++ the size of the array should be known at compile time - before the program executes (and even before the program binary appears on disk) the compiler should know what the values of `M` and `N` are. In your case the values of `M` and `N` are unknown - you are setting them during run time, not compile time. This is allowed in C, but not in C++. Probably your compiler allows such non-standard extensions with default settings. – Paul Nov 09 '15 at 16:49