有谁知道什么可能导致array [n]和array [x](x = n)的回读值彼此不同?
编辑:以下是一个可编译的代码,用于说明我遇到的问题。如果您运行以下代码,您将不会看到任何问题。我只是用它来描述我在原始程序中看到的问题,这是一个100多个类的模拟器。
#include <iostream>
using namespace std;
class MySimulatorImplementationBy100Classes;
class MySimulator {
public:
enum SigList {
SIG0,
SIG1,
SIG2,
// ...
SIG18=18,
SIG19=19,
SIG70=70,
SIG80=80
};
void run() {}
private:
MySimulatorImplementationBy100Classes *impl_;
};
int main() {
MySimulator sim;
// set up the simulation
sim.run();
enum SigAnalysis {
ANALYSIS0,
ANALYSIS1,
ANALYSIS2,
ANALYSIS3,
ANALYSIS4,
ANALYSIS5,
ANALYSIS6,
NUM_ANALYSIS
};
const MySimulator::SigList signal_source[NUM_ANALYSIS] = {
MySimulator::SIG18,
MySimulator::SIG18,
MySimulator::SIG18,
MySimulator::SIG18,
MySimulator::SIG70,
MySimulator::SIG80,
MySimulator::SIG19
};
for(int i=0; i<NUM_ANALYSIS; ++i) {
cout <<signal_source[i]<<"\t" << MySimulator::SIG80 <<"\t" << signal_source[5] << "\t" << i << "\t";
cout << &signal_source[i]<<"\t" << &signal_source[5]<< "\n";
}
}
在我的程序中,输出是
18 80 80 0 0xfffe1c90 0xfffe1ca4
18 80 80 1 0xfffe1c94 0xfffe1ca4
18 80 80 2 0xfffe1c98 0xfffe1ca4
18 80 80 3 0xfffe1c9c 0xfffe1ca4
70 80 80 4 0xfffe1ca0 0xfffe1ca4
173068832 80 80 5 0xfffe1ca4 0xfffe1ca4
168047112 80 80 6 0xfffe1ca8 0xfffe1ca4
虽然我希望它是
18 80 80 0 0xfffe1c90 0xfffe1ca4
18 80 80 1 0xfffe1c94 0xfffe1ca4
18 80 80 2 0xfffe1c98 0xfffe1ca4
18 80 80 3 0xfffe1c9c 0xfffe1ca4
70 80 80 4 0xfffe1ca0 0xfffe1ca4
80 80 80 5 0xfffe1ca4 0xfffe1ca4
19 80 80 6 0xfffe1ca8 0xfffe1ca4
我不知道为什么{i = 5}时signal_source[i]
返回的内容与signal_source[5]
不同,而&signal_source[i]
和&signal_source[5]
相同。
此外,如果我在for
的{{1}}循环之前的某处添加一些虚拟代码
cout
结果会改变:
sim.run();
// dummy print
cout << "dummy\n";
enum SigAnalysis { //...
有没有人知道这里可能出现什么问题?
我正在使用gcc ver 3.4.6。谢谢你的帮助!
答案 0 :(得分:2)
我能想到的唯一事情就是腐败signal_source
(或者是i
)。
发布更完整的代码示例。
更新:这是我的测试程序。它完全符合预期。
enum SigList {
SIG0,
SIG1,
SIG2,
SIG18 = 18,
SIG70 = 70,
SIG80 = 80,
SIG100 = 100
};
const SigList signal_source[7] = {
SIG1,
SIG1,
SIG1,
SIG1,
SIG18,
SIG70,
SIG80
};
int _tmain(int argc, _TCHAR* argv[])
{
cout << signal_source[0] << "\n"; // return 1 (SIG1)
cout << signal_source[1] << "\n"; // return 1 (SIG1)
for(int i=0; i<7; ++i)
{
cout << signal_source[i] << "\n";
}
return 0;
}
答案 1 :(得分:0)
我的第一个建议是在valgrind下运行该程序。我发现这些随机损坏问题可能是通过将未初始化的值传递给系统调用引起的。
这是另一个想法:尝试在整个地方放置随机打印语句,看看问题发生的地方是否发生了变化,这是内存损坏的明确标志。
答案 2 :(得分:0)
也许当你到达for循环时,signal_source
是空的,因为你还没有初始化它,或者因为你在另一个函数中?