简体   繁体   中英

Crash on compiling an array of arrays when size increases

I am trying to return a matrix of integers in a function and I decided to go with a typdef form of matrix. But when I run the project with a function that return a matrix size of 1500 by 1500, the compilation crashed after the project was built. Then I tried to work with different matrix sizes and when I compiled a the code I pasted here with a smaller size (150) for defined Matrix, the problem was solved. This is what I have tested with no problem.

typedef int Matrix[150][150];

int main(){
Matrix mat;
for(int i=0;i<13;i++){
    for(int j=0;j<13;j++){
        mat[i][j]=i;
    }
}
cout << mat[10][11];
return 0;
}

The size of 1500 by 1500 seems very small and I cannot figure out what is the problem it is causing.

Here is the error image:

在此处输入图片说明

That matrix gets allocated on the stack , which is only few MB by default. 1500*1500*4 takes up about 9MB. Large arrays like that are best allocated on the heap (new/delete).

A 1500 x 1500 matrix of ints would be nearly 9MB with 32-bit ints or nearly 18MB with 64-bit ints. That's an enormous stack allocation, and you'er probably hitting a compiler or environment limit. There may be some build-time flags that could address the issue, but a more reasonable solution would be to allocate the object on the heap with new

You're probably running out of stack space - 1500*1500*sizeof(int) is roughly 9 megabytes on a 32 bit system, for example. Use an std::vector or such (it allocates from the heap) or else look up the necessary switch for your compiler to increase your stack size...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM