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,数组首地址是常量,不可以修改。
原文链接: https://www.cnblogs.com/scyq/p/12321444.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;
也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/329921
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!