简体   繁体   English

无法弄清楚为什么程序在C中崩溃

[英]Cant figure out why program is crashing in C

I have this code: 我有以下代码:

#include <stdio.h>
#include <math.h>

#define gridSize    400
void main() {
    float grid[gridSize][gridSize];
    short height[gridSize][gridSize];
    short power[gridSize][gridSize];    
}

I'm using visual studio 2010, the program seems to crash instantly when I run it. 我正在使用Visual Studio 2010,该程序在运行时似乎立即崩溃。 However this code: 但是这段代码:

#include <stdio.h>
#include <math.h>

#define gridSize    400
void main() {
    float grid[gridSize][gridSize];
    short height[gridSize][gridSize];
    //short power[gridSize][gridSize];  
}

Seems to work fine, and the program doesn't crash. 似乎可以正常工作,并且程序不会崩溃。 What could be the problem? 可能是什么问题呢?

Here grid height and power are auto variable and going to store in stack . 在这里, grid heightpowerauto variable ,将存储在stack
In any Os each process has some fixed default size stack. 在任何操作系统中,每个进程都有一些固定的默认大小堆栈。

Here you are allocating too much data on stack so process has no other memory left on stack for other operation. 在这里,您在堆栈上分配了太多的数据,因此进程在堆栈上没有其他内存可用于其他操作。 so it crash 所以它崩溃

you have two option 你有两个选择

1> Increase stack size for this process 1>增加此过程的堆栈大小

On Linux with gcc you can increase it by 在具有gcc的Linux上,您可以将其增加

–stack 16777216 

adding this in gcc command 在gcc命令中添加

2> you can store this data on heap section by using malloc. 2>您可以使用malloc将数据存储在堆部分。

You're allocating too much stack. 您分配的堆栈过多。 Move one or more into heap instead. 而是将一个或多个移入堆。

Just read the name of this website, stack overflow. 刚读了这个网站的名称,栈溢出。 You can: 1, move those three arrays out of main function(maybe you will get a large .exe after compilation if you initialize those arrays). 您可以:1,将这三个数组移出主要功能(如果初始化这些数组,则编译后可能会得到一个较大的.exe)。 or 2, use malloc(). 或2,使用malloc()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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