user3076169
user3076169

Reputation: 1

Valgrind reports memory leak but I don't understand where it occurs

I have written a forward linked list but when I run it through valgrind it reports an memory leak in my remove (const int function) and I can't quite figure out why.

This is the remove function that valgrind complains about. The function is inside the file "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;
  }
}

This is the header file "list.h" belonging to "list.cc".

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();
};

Any help is appreciated!

Upvotes: 0

Views: 114

Answers (2)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 154015

Not the problem you asked about, but this code doesn't work:

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

After delete root the object pointed to by root or copies of root, e.g., current_index, are dead. You need something along those lines:

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

Upvotes: 1

David Schwartz
David Schwartz

Reputation: 182837

This isn't your bug, but this code can't be right:

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

Since current_index = root, the delete root means that current_index now points to a destroyed object, which you dereference in the next line. Oops.

Upvotes: 2

Related Questions