我的阵列有足够的堆栈空间,那么为什么此循环失败? [英] I have enough stack space for my array, so why does this loop fail?
问题描述
int width = 2560;
int height = 1440;
int frameBuffer[width*height];
for (int i = 0; i < width*height; ++i)
frameBuffer[i]=i;
即使您在32位整数的范围内,并且您有足够的内存来分配数组,此代码也可以锁定进程?
This code locks the process up, even thou I am well within the bounds of 32 bit integers and I have plenty of memory to allocate the array?
BTW具有讽刺意味的,不是吗?在名为stackoverflow的网站上询问堆栈溢出错误:)
BTW Ironic, isn't it? Asking about a stack overflow error on a site called stackoverflow :)
推荐答案
您可能超出了可用的堆栈空间,从而导致溢出.在堆栈上放置如此大的数组不是一个好主意.
You are probably exceeding the available stack space, causing an overflow. It is not a good idea to have such big arrays on the stack.
您可以自己分配缓冲区,而不是使用非标准的VLA(可变长度数组):
Instead of using the non-standard VLA's (variable-length arrays), you can allocate the buffer yourself:
size_t width = 2560;
size_t height = 1440;
int *frameBuffer = new int[width * height];
for (size_t i = 0; i < width * height; ++i)
frameBuffer[i] = i;
...
delete[] frameBuffer;
还请注意 size_t
而不是 int
的用法.关于分配大小,您应该坚持使用 size_t
,因为不能总是保证 int
能够容纳足够大的大小.
Also note the usage of size_t
rather than int
. You should stick with size_t
when it comes to allocation sizes, since an int
is not always guaranteed to be capable of holding a size large enough.
这篇关于我的阵列有足够的堆栈空间,那么为什么此循环失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!