Stack overflow C++

2019-01-20 10:59发布

This is my code. When I access dtr array in initImg function it gives a stack overflow exception. What might be the reason?

#define W 1000
#define H 1000
#define MAX 100000 
void initImg(int img[], float dtr[])
{
    for(int i=0;i<W;i++)
        for(int j=0;j<H;j++)
            img[i*W+j]=255;

    for(int j=0;j<H;j++)
    {
        img[j] = 0;
        img[W*(W-1)+j] = 0;
    }
    for(int i=0;i<W;i++)
    {
        img[i*W] = 0;
        img[i*W+H-1] = 0;
    }
    for(int i=0;i<W;i++)
        for(int j=0;j<H;j++)
        { 
            if(img[i*W+j]==0)
                dtr[i*W+j] = 0;    // <------here
            else
                dtr[i*W+j] = MAX;  // <------here
        }
}
int main()
{
    int image[W*H];
    float dtr[W*H];
    initImg(image,dtr);
    return 0;
}

8条回答
相关推荐>>
2楼-- · 2019-01-20 11:09

In addition to the stack overrun, you have another problem -- one which is masked by your definitions of W and H.

for(int i=0;i<W;i++)
    for(int j=0;j<H;j++)
    { 
        if(img[i*W+j]==0)
            dtr[i*W+j] = 0;    // <------here
        else
            dtr[i*W+j] = MAX;  // <------here
    }

Your i loop should count from 0 to H-1, rather than W-1 (and the j loop should swap as well). Otherwise your code will only work correctly if W==H. If WH you will overrun your buffers.

This same problem exists elsewhere in your code sample as well.

查看更多
Viruses.
3楼-- · 2019-01-20 11:11

Your compiler will define the stack size. A way to get around this is to dynamically allocate your arrays using std::vector array_one(W*H).

查看更多
登录 后发表回答