I'm curious as to why I cannot delete pointer cur in my d_ordered_insert function, since isn't it just a copy of the front pointer? (When I uncommented the delete cur; the program crashes.
#include <iostream>
#include <string>
usingnamespace std;
struct dll_node//doubly linked-list node
{
string data_;
dll_node* next;
dll_node* back;
};
dll_node* d_ordered_insert(string node_data_, dll_node** front, dll_node** end)
{
dll_node* cur = *front;//NB: need this ptr to pt to cur potential node where newNode will be inserted before or after the node cur pts to
dll_node* newNode = new dll_node;
newNode->data_ = node_data_;
if ( *front == NULL && *end == NULL )//if empty list, then newNode is the front and end of list!
{
*front = newNode;
*end = newNode;
newNode->next = NULL;
newNode->back = NULL;
return *front;
}
if ( *front != NULL && cur == *front && newNode->data_ < cur->data_)//if newNode is smallest (cur initially pts to front of list so cur == *front checks that
{
newNode->next = *front;
newNode->back = NULL;
*front = newNode;
// delete cur;//Q: Why can't I delete this? Isn't it a copy of the front ptr?
return *front;
}
for ( ; cur != NULL; cur = cur->next )//if newNode goes somewhere else in list
{
if ( cur->next != NULL && newNode->data_ < cur->data_)//if newNode smaller than some node and not end of list, link in new node
{
(cur->back)->next = newNode;
newNode->next = cur;
newNode->back = cur->back;
return *front;
}
elseif ( cur->next == NULL )//if we are @ EOL (end of list) so new node must be largest node
{
cur->next = newNode;
newNode->back = cur;
newNode->next = NULL;
*end = newNode;
return *front;
}
}
}
int main()
{
dll_node* front = NULL;
dll_node* end = NULL;
d_ordered_insert("ze", &front, &end);
d_ordered_insert("a", &front, &end);
return 0;
}
Because your not deleting the pointer your deleting the memory it points to. In this case you appear to be adding a node as the new front node then deleting the next node (old front).
Edit: The memory the pointer itself is stored will get freed when it is out of scope.