For循环变量无缘无故地下地狱

For loop variable going to hell for seemingly no reason?

本文关键字:地下地 地狱 地下 无缘无故 循环 变量 For      更新时间:2023-10-16

我遇到了一个看起来很不起眼的bug。我的程序包括长时间循环一些代码,并最终在循环中运行一些函数。奇怪的是,在我运行一个特定的函数之后,我的for循环变量'z'从3200跳到1059760811左右(它每次都在变化)。这个函数并没有自然地使用循环变量,所以我真的不知道这里发生了什么。

整个代码太长,不能粘贴在这里,所以我将尝试只粘贴重要的部分,将相关函数放在前面,然后是for循环:

void enterdata(float dpoint,int num){
        autodata[num] += dpoint;
    }
float autocorr(){
        float autocorrelation = 0;
        for(int a = 0; a<SIZEX; a++)
        {
            for(int b = 0; b<SIZEY; b++)
            {
                if(grid[a][b] == reference[a][b]){autocorrelation++;}
            }
        }
        autocorrelation /= SIZEX*SIZEY;
        autocorrelation -= 0.333333333333;
        return autocorrelation;
    }
for (long z = 0.0; z<MAXTIME; z++)
    {
        for (long k=0; k<TIMESTEP; k++)
        {
            grid.pairswap();
        }
        if (z == autostart_time)
        {
            grid.getreference();
            signal = 1; // signal is used in the next if statement to verify that the autocorrelation has a reference.
        }
        if ((z*10)%dataint == 0)
        {
            if (signal == 1) {
            //!!! this is the important segment!!!
            cout << z << " beforen";
            grid.enterdata(grid.autocorr(),count);
            cout << z << " aftern";
            cout << grid.autocorr() << " (number returned by function)n";
            count++;
            }
        }
        if (z%(dataint*10) == 0) { dataint *= 10; }
    }

从代码中标记的"重要段",这是我的输出:

3200,1059760811后,0.666667(函数返回的数字)

很明显,在函数过程中'z'变量发生了一些奇怪的事情。我也确信这是enterdata函数,而不是分别运行的自相关函数。

我不知道如何解决这个问题,或者发生了什么。帮助吗? ! ? ! ?

谢谢!

看起来您可能在enterdata函数中有堆栈溢出问题。

在数组开始之前或数组结束之后写入将导致未定义的行为,包括对堆栈上已经存在的变量进行写入。

@WhozCraig是对的,被调用的函数覆盖堆栈似乎是最可能的解释。

您应该能够在调试器中找到如何在any change to the memory at address of z上中断,这将快速提供准确的诊断。

对于Visual Studio(例如),请参见这里。