Extensive array causes the program to stop working

1

I have the following problem, when I define an array that is too large, for example: int matriz[2000][2000] , compile and command to run, the program stops working. I just tested it in Windows and it appears that classic message ".exe has stopped working" .

#include <stdio.h>

int main() {
    int matriz[2000][2000];
    return 0;
}

This is the code as you can see I just declare array, and this is enough to stop working at the time of execution. If I downsize works, I've already tested it, but I need a gigantic array myself.

I'm using the windows 7 professional . IDE DEV-C ++; gcc compiler 4.8.1 32 bits

    
asked by anonymous 10.10.2015 / 15:11

2 answers

3

You are getting a stack overflow .

The array is being allocated from stack and it has size limit. Large objects must be allocated in heap , via malloc() . Of course this complicates matters a little. But it's the only way. There's a lot you need to learn about memory management before you do what you want.

#include <stdio.h>
#include <stdlib.h>
#define linhas 2000
#define colunas 2000

int main() {
    int * matriz = malloc(linhas * colunas * sizeof(int));
    matriz[0 * linhas + 0] = 0; //coloca um valor na primeira posição da "matriz"
    printf("%d", matriz[0 * linhas + 0]); //claro que neste caso se colocasse apenas 0 funcionaria
    free(matriz);   
    return 0;
}

See running on ideone .

Read about difference between arrays and pointers .

I insist that there is a lot to learn about memory management before going out to do more complex things. If you do not want to deal with these details, C is not a language for you.

Enjoy and choose a better IDE.

    
10.10.2015 / 15:33
1

A simple alternative to solve this problem is to allocate the array at compile time instead of allocating runtime on the stack.

int main() {
    static int matriz[2000][2000];
    return 0;
}

This is equivalent to allocating the array as a global variable except that the array is only visible within main .

    
14.10.2015 / 16:24