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,数组首地址是常量,不可以修改。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步