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

总结:

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

ps:使用new语法,为自定义结构类型,的局部变量分配指定内存空间。前提是:要把局部变量的值确定下来?

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值