【问题标题】:Heap use after free err释放错误后的堆使用
【发布时间】:2021-12-04 05:08:28
【问题描述】:

在 Leetcode 中出现免费错误后获得堆使用,似乎不明白根本原因。你们能帮我吗?

几乎所有东西都在堆栈上声明。我唯一的怀疑是我在堆栈 multiset temp 上创建的浅拷贝,但是您不能释放堆栈上没有在堆上创建的任何东西?

class Solution {
public:

    void earn_points(multiset<int> points,int currpoint, int& max){

        set<int> unique;


        if(points.size() == 0){
             cout <<"finalscore="<< currpoint << " "<<endl;

            if(currpoint > max){
                max = currpoint;
            }
        }

        multiset<int> temp = points;

        for(auto it=points.begin(); it != points.end(); ++it){

            int num = *it;

            if(unique.find(num) != unique.end()){
                continue;
            }

            unique.insert(num);

            int delete_num1 =  num + 1;
            int delete_num2 =  num - 1;

            points.erase(it);

            if(points.find(delete_num1)  != points.end())
                 points.erase(delete_num1);

            if(points.find(delete_num2)  != points.end())
                    points.erase(delete_num2);

             cout << num <<"   ";

             for(auto i : points){
                 cout << i <<" ";
             }

             cout << endl;


             earn_points(points,currpoint + num,max);


             points = temp;

          }

    }

    int deleteAndEarn(vector<int>& nums) {

        multiset<int> points(nums.begin(),nums.end());

        int max = INT32_MIN;

        earn_points(points,0,max);

        return max;
    }
};

【问题讨论】:

标签: c++ heap-memory


【解决方案1】:

您的问题很可能在这里:

points.erase(it);

if(points.find(delete_num1)  != points.end())
      points.erase(delete_num1);

if(points.find(delete_num2)  != points.end())
      points.erase(delete_num2);

当你从多重集中删除东西时,它会使迭代器无效,所以当你点击迭代器引用你在 for... 循环中删除的东西时,你引用的东西不再存在。

【讨论】:

  • 正确,但未能指出已擦除的迭代器在何处被重用。明显的重用是++itfor 的迭代表达式中。我没有看过去的代码,所以可能还有更多。
猜你喜欢
  • 2020-11-13
  • 2021-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-18
  • 1970-01-01
  • 1970-01-01
  • 2015-06-15
相关资源
最近更新 更多