For循环变量无缘无故地下地狱
For loop variable going to hell for seemingly no reason?
我遇到了一个看起来很不起眼的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(例如),请参见这里。
相关文章:
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- Eigen如何在容器循环中干净地附加矩阵
- 在c++中检查长方体是否尽可能快地重叠(无迭代)
- 有效地使用std::unordered_map来插入或增加键的值
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- C++为线程工作动态地分割例程
- 如何使用gdb制作一个可以漂亮地打印每个对象的C++函数
- 通过错误处理,在C++中可靠地获得用户十六进制输入
- 如何在C++中高效地构造随机骰子
- 有没有办法知道Tracer是否成功地完全连接到了jaegerclientcpp中的jaeger后端服务器
- std::vector::迭代器是否可以合法地作为指针
- 如何正确地将分支添加到已存在的树中
- 如何在C++中递归地按相反顺序打印集合
- 如何优雅地切片对象
- 如何正确地将带有指针的数组传递给函数
- 违反const正确性:我应该现实地期待什么问题
- 如何创建函数管道,以便函数一个接一个地运行?
- 变量被错误地设置为 204
- 有没有办法简单地从 GPU 调用多个 cpp 输出文件?
- 方便地对C++中的所有字符串文字进行模糊处理