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