I have enough stack space for my array, so why does this loop fail?

后端 未结 3 380
太阳男子
太阳男子 2021-01-16 05:56
int width = 2560;
int height = 1440;
int frameBuffer[width*height];
for (int i = 0; i < width*height; ++i)
    frameBuffer[i]=i;

This code locks

相关标签:
3条回答
  • 2021-01-16 06:23

    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<int> frameBuffer(width * height);
    
    0 讨论(0)
  • 2021-01-16 06:29

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

    0 讨论(0)
  • 2021-01-16 06:33

    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:

    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. 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.

    0 讨论(0)
提交回复
热议问题