C++ delete报错解析

C++ delete报错

今天写了如下代码

#include <iostream>
#include <algorithm>
using namespace std;


int main() {
	int n, s, a, b;
	int ans = 0;
	cin >> n >> s;
	cin >> a >> b;
	int* p = new int[n];
	int temp;
	int length = 0;
	for (int i = 0; i < n; i++) {
		cin >> temp;	  // now temp is the height
		if (temp <= a + b) {
			cin >> *p;    // input the strength cost
			p++;
			length++;
		}
		else cin >> temp; // trash data dealing
	}
	sort(p, p+length-1);
	p -= length;
	while (s > 0) {
		ans++;
		s -= *p;
		p++;
	}
	delete [] p;
	cout << ans;
}

编译没有报错,但是运行的时候报错了。原因是delete语句。

出错现象:

执行delete语句时,程序卡死。将delete注释掉,程序运行正常,但是发生了内存泄漏。

原因:

p作为指向堆内存的指针,指向的是数组的首地址。而我更改了p的地址,如代码中的p++。

解决方案:

能加const就const,数组首地址是常量,不可以修改。

posted @   scyq  阅读(1739)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示