I have a simple doubly linked list example that I’m working on, but for some reason I keep getting the error: pointer being freed was not allocated when I try to delete
Here is a code snipet of the insert at end of list method
template <class T>
void List<T>::insertAtEnd(T *o)
{
node *newNode = new node;
newNode->o = o;
newNode->next = NULL;
newNode->prev = last;
if(last != NULL)
last->next = newNode;
last = newNode;
if(first == NULL)
first = newNode;
delete(newNode); // This delete call will usually be in another method
} // It is just here right now for testing
This class has two instance fields, a pointer to the beginning of the list and a pointer to the end, first and last respecitvely. Each node is a struct as follows:
struct node {
node *next;
node *prev;
T *o;
};
So far I have only tested with inserting 1 node, but I always get the same error. However, if I comment out the lines
if(first == NULL)
first = newNode;
it works. Help please? Thanks
EDIT: Both first and last start as NULL.
You have, unfortunately, not provided the entirety of your code. You’ve omitted the section containing your error, so I must speculate as to the exact cause.
The error you are seeing indicates that
deleteis being called on an address that was not produced vianew. This probably means you are inadvertently doing a value assignment, instead of a pointer assignment, and then attempting to free the copied (stack-allocated) variable. One specific way this could happen is if you attempt todelete mynode->o, sinceocould be the address of a stack variable.Double-check that every type which should be a
node*is anode*, not anodeor anode**. Compiling your code with-Wall -Wextramay produce helpful additional warnings and should be a first debugging step if not a general practice.If your types and assignments are all correct, you may be using a C++ library or compiler that doesn’t give you particular double-free messages; this would expand the scope of the error you see to include freeing the same memory twice. Try printing an address just before you free it (or using a debugger to the same effect). When you see the same address come up twice, that’s it.
This may be obvious, but you can’t have the
deletecall there and have your function work right.firstandlastwill point to freed memory. Felt that needed to be said, just in case.