views:

73

answers:

3
+2  A: 

The destructor of the VectorNode class deletes the object pointer to by the t_next pointer. Calling delete on the toRemove pointer means that the destructor of that VectorNode object gets called, and then the next one, and then the next one etc. etc.

So basically, when you delete toRemove, you delete toRemove and all the objects that come after this. This causes the tailNode's t_prev to point to memory that you have already freed, and you then try dereferencing those pointers in your Index function, and that's not a good thing.

Jacob
+1  A: 

When you delete a VectorNode that has its t_next member pointing to some other node, the destructor of VectorNode will delete that other node (which in turn might go on to delete further nodes).

When you remove a node from the middle of a list with Remove(), the t_next of this node will point to the further nodes of the list. When this node is deleted, the destructor will also delete all the nodes following it in the list. Continuing to use this half-deleted list it will result in all kinds of problems.

Other random observations:

  • Why is size a int* instead of a normal int or size_t? I can't see any reason why this should be a pointer.
  • new VectorNode<var>(*(new var)) should really be new VectorNode<var>(var()) to not unnecessarily leak memory.
  • The t_next != NULL test before delete is unnecessary
  • Are you planning to create classes deriving from VectorNode<>? If not, than there is no reason why the methods would need to be virtual.
  • Using 1-based indexing in Add() is unusual, one would expect zero-based indexing

Also I feel obliged to tell you that there are standard library containers like std::list<> and std::vector<> which implement this kind of structures.

sth
+1  A: 

Calling remove deletes a node, but deleting a node deletes all the nodes->next

~VectorNode()
{
    if (t_next != NULL)
        delete t_next;
}

so deleting element 2 of your 1 based vector kills all the other elements as you have experienced, and there is no longer an element 3 to investigate

Greg Domjan