C++ delete[] 出错

错误代码:

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 DETECTEDCRT 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(); // 读取输入队列中的回车符

总结:

可以通过输入的方式初始化局部变量。


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部