错误代码:
const int SIZE = 20;
struct car
{
char producer[SIZE];
int date;
};
int main()
{
int n = 0;
car* pt = new car[n];
cout << "How many cars do you wish to catalog? ";
cin >> n;
cin.get(); // 读取输入队列中的回车符
for (int i = 0; i < n; ++i)
{
cout << "Car #" << (i + 1) << ":" << '\n'
<< "Please enter the make: ";
cin.get((pt + i)->producer, SIZE);
cout << "Please enter the year made: ";
cin >> (pt+i)->date;
cin.get();
}
cout << "Here is your collection:" << '\n';
for (int i = 0; i < n; ++i)
{
cout << (pt + i)->date << " " << (pt + i)->producer << endl;
}
delete[] pt;
system("pause");
return 0;
}
输出结果:
可以正常输出。但输出之后出现Debug Error!HEAP CORRUPTION DETECTED、CRT detected that the application wrote to memory after end of heap buffer.
原因:
逐过程调试,发现程序运行到delete[] pt;
出现错误(如图所示)。
Heap Corruption:当输入超出了预分配的空间大小,就会覆盖该空间之后的一段存储区域,这就叫Heap Corruption
引用的博客
综上,定位错误源:
car* pt = new car[n];
想不通,从源头逐步扩大范围:
int n = 0;
car* pt = new car[n];
cout << "How many cars do you wish to catalog? ";
cin >> n;
发现该代码区间由上至下运行逻辑出现错误、模糊。
对于car* pt = new car[n];
语句,对变量n的有两次赋值。
从上至下
第一次是因为n有默认的初始值时,new分配了一块内存空间
int n = 0;
car* pt = new car[n];
第二次是通过cin输入赋值,new又分配了一块内存空间
car* pt = new car[n];
cin >> n;
这可能造成???不懂 待续、、、、、、、、、、、待今后解答
改正:
int n;
cout << "How many cars do you wish to catalog? ";
cin >> n;
car* pt = new car[n];
cin.get(); // 读取输入队列中的回车符
总结:
可以通过输入的方式初始化局部变量。
ps:使用new语法,为自定义结构类型,的局部变量分配指定内存空间。前提是:要把局部变量的值确定下来?