Debug assertion failed

The problem is that the function list::Subset(list subset) takes its argument by value causing a copy of the list to be made. Since you did not follow the Rule of Three (as noted in Chris’ comment) a shallow copy is made. This means that two instance of list “own” the pointers. When the Subset function returns the copy goes out of scope causing the nodes to be deleted. When the program exits the original copy of the list goes out of scope and it attempts to delete the same nodes again causing the assertion.

You can get around this by taking the argument by reference instead of by value. Change

class list
{
    // ... snip ...
    bool Subset(list subset);
    // ... snip ...
};

to

class list
{
    // ... snip ...
    bool Subset(list& subset);
    // ... snip ...
};

and

bool list::Subset(list subset)
{
    // ... snip ...
}

to

bool list::Subset(list& subset)
{
    // ... snip ...
}

Some other suggestions:

  1. Either implement a proper copy constructor or declare one and make it private to prevent copies from being made
  2. Learn const correctness. Since Subset does not modify the contents of the list passed to it you can declare it bool list::Subset(const list&) const instead. This will require list::RetHead() to be declared const as well.
  3. bool flag in list::Subset is not initialized meaning that any value can be returned if your logic is not correct.

Leave a Comment