简体   繁体   English

我的阵列有足够的堆栈空间,为什么这个循环失败?

[英]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;

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? 即使您在32位整数的范围内,并且您有足够的内存来分配数组,此代码也会锁定该过程?

BTW Ironic, isn't it? BTW具有讽刺意味的,不是吗? Asking about a stack overflow error on a site called stackoverflow :) 在名为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. 在堆栈上放置这么大的数组不是一个好主意。

Instead of using the non-standard VLA's (variable-length arrays), you can allocate the buffer yourself: 您可以自己分配缓冲区,而不是使用非标准的VLA(可变长度数组):

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;

Also note the usage of size_t rather than int . 还要注意size_t而不是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. 关于分配大小,您应该坚持使用size_t ,因为不能总是保证int能够容纳足够大的大小。

The way you declare it, the array is probably allocated on the stack (I am not sure though). 声明方式,数组可能分配在堆栈上(不过我不确定)。 You should try to allocate it dynamically, ideally using an std::vector : 您应该尝试动态分配它,最好使用std::vector

std::vector<int> frameBuffer(width * height);

the number of elements the array is going to hold, must be a constant value, since arrays are blocks of non-dynamic memory whose size must be determined before execution. 数组要保留的元素数必须为常数,因为数组是非动态内存的块,其大小必须在执行之前确定。 In order to create arrays with a variable length dynamic memory is needed 为了创建长度可变的数组,需要动态内存

use int frameBuffer[2560*1440]; 使用int frameBuffer[2560*1440];

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

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