Possible Duplicate:
What is the best way to check for memory leaks in c++?
I’m writing a doubly linked list in C and most of it is implemented and working(I only need to fix some minor logic errors in traversing and possibly freeing).
Question:
How can I be absolutely sure that I’m freeing all the memory that I allocate? I would also like to know if there are any techniques to optimizing my allocation. Any tips or hints on how it works or links to tutorials are appreciated as well.
I’m pretty much a beginner, so any other tips in fixing my coding techniques would be appreciated. I use gdb to debug and I’m running on Archbang Linux x86_64.
Thank you for your help.
Here are the structures of the doubly linked list:
typedef struct node_element{
double data;
} element;
typedef struct node_t{
struct node_t *prev;
struct node_t *next;
struct node_element element;
} node;
typedef struct list_t{
struct node_t *head;
struct node_t *tail;
} list;
This is how I create a list:
list *createList(){
list *temp = malloc(sizeof(list));
temp->head = malloc(sizeof(node));
temp->tail = malloc(sizeof(node));
temp->head->prev = NULL;
temp->head->next = temp->tail;
temp->tail->prev = temp->head;
temp->tail->next = NULL;
return temp;
}
New nodes:
node *newNode(element * element){
node *current = malloc(sizeof(node));
current->element.data = element->data;
return current;
}
Removing individual nodes, not very relevant to my question, but may be useful:
node *removeNode(list * list, node * current){
if (current->prev == NULL)
list->head = current->next;
else
current->prev->next = current->next;
if (current->next == NULL)
list->tail = current->prev;
else
current->next->prev = current->prev;
free(current);
return NULL;
}
And now the important part, when I’m done with a list I call this function:
list *removeList(list * list){
node *temp; //Revised.
//node *temp = malloc(sizeof(node));
while (list->head != NULL){
temp = list->head->next;
free(list->head);
list->head = temp;
}
return NULL;
}
like so:
a_list = removeList(a_list);
Amongst the multitude of features it provides, Valgrind will allow you to check for memory leaks. It does this by dynamically instrumenting the memory management functions.
You might use a command like this: