首页 > 编程语言 > 详细

C++ delete报错解析

时间:2020-02-17 14:51:53      阅读:73      评论:0      收藏:0      [点我收藏+]

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

C++ delete报错解析

原文:https://www.cnblogs.com/scyq/p/12321444.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!