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,数组首地址是常量,不可以修改。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM