栈空间太大超过工程设定值引发的进程崩溃

13次阅读

共计 630 个字符,预计需要花费 2 分钟才能阅读完成。

一. 栈的简介

栈空间在进程中主要用来存放局部变量的值,在 windows 下使用 visual studio 作为编译器,默认的栈空间大小为 1M。
二. 示例代码
#include <iostream>
void teststacksize2()
{
char szArray[600000] = {0};//600,000byte
std::cout<<“teststacksize2″<<std::endl;
}
void teststacksize1()
{
char szArray[600000] = {0};//600,000byte
std::cout<<“teststacksize1″<<std::endl;
teststacksize2();
}
int main(int argc, char* argv[])
{
teststacksize1();
return 0;
}

三. 程序运行效果如图

四. 解决此问题的方法
1. 修改工程中 stack reserve size 的大小,工程右键 Properties->Linker->System->Stack Reserve Size 中进行修改,改为 10M 或者更大。此示例程序中 teststacksize1 和 teststacksize2 方法中一共申请了 1,200,000 个字节。此方法不推荐,因为可能会有更大字节的局部变量。
2. 将 char szArray[] 改为 stack,亦可避免崩溃,因为静态的局部变量类似于全局变量,在全局区。
3. 将 szArray new 出来存在在堆上,推荐此种方法。

正文完
 0