瓦尔格林德报告内存泄漏,但我不明白它发生在哪里



我已经编写了一个前向链表,但当我通过valgrind运行它时,它报告了我的remove(const-int函数)中的内存泄漏,我不太清楚原因。

这是valgrind抱怨的删除功能。该函数位于文件"list.cc".中

void Plist::remove(const int pos)
{
  current_index = root;
  if( pos == 0 )
  {
    delete root;
    root = current_index -> pointer;
  }
  else
  {
    for(int n = 0; n<pos-1; ++n)
    {
      current_index = current_index -> pointer;
    } 
    index * new_link = current_index -> pointer -> pointer;
    delete current_index -> pointer;
    current_index -> pointer = new_link;
  }
}

这是属于"list.cc".的头文件"list.h"

class Plist
{
private:
  class index
  {
  public:
    index(int value, index * ptr);
    index(int value);
    int val{0};
    index * pointer{nullptr};
  };

  index * root = nullptr;
  index * current_index = nullptr;
public:
  Plist(){}
  ~Plist();
  Plist (Plist& lst);
  Plist& operator=(Plist& lst);
  void insert(const int val);
  void remove(const int pos);
  void print();
};

感谢您的帮助!

这不是你的错误,但这段代码不可能是正确的:

current_index = root;
if( pos == 0 )
{
  delete root;
  root = current_index -> pointer;
}

由于current_index = rootdelete root意味着current_index现在指向一个已销毁的对象,您可以在下一行中取消引用该对象。哎呀。

不是您询问的问题,但此代码不起作用:

current_index = root;
if( pos == 0 )
{
    delete root;
    root = current_index -> pointer;
}

delete root之后,由rootroot的副本(例如current_index)指向的对象是死的。你需要这样的东西:

current_index = root;
if (pos == 0) {
    current_index = current_index->pointer;
    delete root;
    root = current_index;
}

相关内容

最新更新