我的程序似乎总是产生荒谬的错误.请为我提供指示.以下代码段剪切掉所有不相关的部分.谢谢.
代码段的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!
}
Run Code Online (Sandbox Code Playgroud)
样本输出
0:200320 0
1:201581 0
2:201582 0
3:201583 0
4:0 0
5:0 0
cntPeopleByAge:1799119387:0:0
Run Code Online (Sandbox Code Playgroud)
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";
}
Run Code Online (Sandbox Code Playgroud)
和这里
std::cout << "cntPeopleByAge:" << cntPeopleByAge[ AG_TOTAL + 1 ] << "\n";
Run Code Online (Sandbox Code Playgroud)
你出局了.最后一个有效索引是AG_TOTAL.
你有未定义的行为(UB).这些错误与UB一样荒谬.