声明大数组时出现堆栈溢出异常 [英] Getting a stack overflow exception when declaring a large array

查看:50
本文介绍了声明大数组时出现堆栈溢出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码为我生成了堆栈溢出错误

The following code is generating a stack overflow error for me

int main(int argc, char* argv[])
{
    int sieve[2000000];
    return 0;
}

我该如何解决这个问题?我正在使用 Turbo C++,但希望将我的代码保留在 C 中

How do I get around this? I am using Turbo C++ but would like to keep my code in C

谢谢你的建议.上面的代码只是举例,我实际上在函数中而不是在 sub main 中声明了数组.此外,我需要将数组初始化为零,所以当我在谷歌上搜索 malloc 时,我发现 calloc 非常适合我的目的.

Thanks for the advice. The code above was only for example, I actually declare the array in a function and not in sub main. Also, I needed the array to be initialized to zeros, so when I googled malloc, I discovered that calloc was perfect for my purposes.

Malloc/calloc 也比在堆栈上分配有优势,允许我使用变量声明大小.

Malloc/calloc also has the advantage over allocating on the stack of allowing me to declare the size using a variable.

推荐答案

您的数组太大而无法放入堆栈,请考虑使用堆:

Your array is way too big to fit into the stack, consider using the heap:

int *sieve = malloc(2000000 * sizeof(*sieve));

如果你真的想改变堆栈大小,看看这个文件.

If you really want to change the stack size, take a look at this document.

提示: - 不要忘记在不再需要动态分配的内存时释放它.

Tip: - Don't forget to free your dynamically allocated memory when it's no-longer needed.

这篇关于声明大数组时出现堆栈溢出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆