I'm creating a simple linked list in C in order to get used to some memory management. I've defined a node structure that holds a char* key, char* value and a node* next.
void newnode(node *n, int x, int y)
{
n->key = malloc(x*sizeof(char));
n->value = malloc(y*sizeof(char));
}
//This how i create a new node given a key and value to make sure that I have allocated the proper amount of space. x and y are the strlengths of the key and value being added.
// In the add function I use the following two lines (when it is valid to add a new key value pair)
current->next = malloc(sizeof(node));
node_newnode(current->next,strlen(key),strlen(value));
// My remove function then searches for a key and if that key exists in the structure it removes that node. I use a delete point to keep track of the node needing deletion.
void remove(dict *d, const char *key)
{
node* delete;
node* current;
current = d->head;
while(current->next != NULL){
if(strcmp(current->next->key,key)==0){
delete = current->next;
if(current->next->next != NULL)
current = current->next->next;
else
current->next = NULL;
node_destroy(delete);
break;
}
current = current->next;
}
}
// Here is the node_destroy function I used in remove.
void node_destroy(node* delete)
{
free(delete->key);
free(delete->value);
free(delete);
}
I'm having problems with this remove function. Essentially it seems that it is not deleting key value nodes properly and is leaving remnants of a node instead of completely removing it. I have no idea why this is possible especially when I set pointers to point past the node needing deletion. At worst case, I feel I should just be leaking memory, but somehow these nodes aren't getting deleted and are still part of the structure when I print out the dictionary. I'm sort of new to having to pay attention to the layout of memory and I can't really see whats going wrong.
Any suggestions?
P.S. Is my node destroy function not properly freeing memory?