Extensive matrix makes the program stop working

Asked

Viewed 241 times

1

I have the following problem, when I define a matrix that is very large, for example: int matriz[2000][2000], compile and run, the program stops working. I tested only on 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 matrix, and that’s enough to stop working at the time of execution. If I decrease the size works, I’ve tested it, but I need a gigantic matrix even.

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

  • '#include <stdio. h> int main() { int matrix[2000][2000]; Return 0; }'

  • Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? You need something to be improved?

2 answers

3

Are you getting a stack overflow.

The array is being allocated from stack and it has size limit. Large objects should be allocated in the heap, through the malloc(). Of course, this complicates things 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);   
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Read about the difference between arrays and pointers.

I insist there’s a lot to learn about memory management before you go out and do more complex things. If you don’t want to deal with these details, C is not a language for you.

Take advantage and choose a better IDE.

  • Ok, dynamic allocation is the stop of the time, or start studying. Thank you very much for your help.

  • going************

1

A simple alternative to solve this problem is to allocate the matrix at compile time rather than at runtime on the stack.

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.