我的程序似乎总是会产生荒谬的错误。 请给我指路。下面的代码段删掉了所有不相关的部分。 谢谢。
代码段A部分似乎没有正确初始化数组,如何调试? 代码段的 B 部分总是崩溃,我是否遗漏了什么?
typedef unsigned long T_PSIZE;
int main()
{
int AG_TOTAL = 6 ;
/* part A1 */
T_PSIZE* cntPeopleByAge = new T_PSIZE[AG_TOTAL + 1];
/* part A2 - originally i use static array like this, but it also fails */
//T_PSIZE cntPeopleByAge T_PSIZE[AG_TOTAL + 1];
for (int i = 0; i < (AG_TOTAL + 1); i++)
{
std::cout << i << ":" << cntPeopleByAge[i] << "\t";
cntPeopleByAge[i] = 0;
std::cout << cntPeopleByAge[i] << "\n";
}
std::cout << "cntPeopleByAge:" << cntPeopleByAge[ AG_TOTAL + 1 ] << "\n";
/* part B */
delete [] cntPeopleByAge;
return 0; // <--- crash here!
}
示例输出
0:200320 0
1:201581 0
2:201582 0
3:201583 0
4:0 0
5:0 0
cntPeopleByAge:1799119387:0:0
- 平台:win 7 x64
- 编译器:TDM-GCC x64
最佳答案
for (int i = 0; i < (AG_TOTAL + 1); i++)
{
std::cout << i << ":" << cntPeopleByAge[i] << "\t";
// ^^^^^^^^^^^^^^^^
// You're reading uninitialized memory here
cntPeopleByAge[i] = 0;
std::cout << cntPeopleByAge[i] << "\n";
}
这里
std::cout << "cntPeopleByAge:" << cntPeopleByAge[ AG_TOTAL + 1 ] << "\n";
你越界了。最后一个有效索引是 AG_TOTAL
。
您有未定义的行为 (UB)。这些错误只是和 UB 一样荒谬。
关于c++ - CPP : Mysterious error for array initialization and crash?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12445253/