我遇到了一个似乎非常晦涩难懂的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 << " before\n";
grid.enterdata(grid.autocorr(),count);
cout << z << " after\n";
cout << grid.autocorr() << " (number returned by function)\n";
count++;
}
}
if (z%(dataint*10) == 0) { dataint *= 10; }
}来自代码中标记的“重要片段”,这是我的输出:
3200之前,1059760811之后,0.666667 (函数返回的数字)
显然,在函数执行过程中,'z‘变量发生了一些奇怪的事情。我也确信它是enterdata函数,而不是分别运行每个测试的自相关函数。
我不知道如何解决这个问题,也不知道发生了什么。救命?!?!?
谢谢!
发布于 2013-03-16 00:25:44
看起来您的enterdata函数中可能存在堆栈溢出问题。
在数组开始之前或数组末尾之后写入会导致未定义的行为,包括覆盖堆栈上已有的变量。
发布于 2013-03-16 00:25:52
@WhozCraig是对的,被调用函数的堆栈覆盖似乎是最可能的解释。
您应该能够在您的调试器中找到如何在any change to the memory at address of z上中断,这将很快提供准确的诊断。
例如,对于Visual Studio,请参见here。
https://stackoverflow.com/questions/15436820
复制相似问题