Hi everybody o/.
I'm studing Linked List in C. I made two functions: add ( add data on the list) and destroy (destroy the list). For now, it's just this two functions that i need, but the function destroy doesn't works well. When I call the function destroy only the first two nodes are destroyed and I can't find out why the others not.
If I call display after destroy, the display continues showing the data after the second node.
Can anyone explain me what I'm doing wrong?
Here my complete code:
/*
* File: main.c
* Author: donda
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
struct t_ddclist {
int index;
char value[256];
struct t_ddclist *next;
};
typedef struct t_ddclist ddclist;
ddclist *createDDCList();
int addDDCList(ddclist *list, char *value);
void destroyDDCList(ddclist *list);
void displayDDCList(ddclist *list);
/*
*
*/
int main(int argc, char** argv) {
ddclist *myList = createDDCList();
if (!myList) {
printf("Error on create list\n");
exit(-1);
}
addDDCList(myList,"Test1");
addDDCList(myList,"Test2");
addDDCList(myList,"Test3");
addDDCList(myList,"Test4");
addDDCList(myList,"Test5");
addDDCList(myList,"Test6");
displayDDCList(myList);
destroyDDCList(myList);
return (EXIT_SUCCESS);
}
ddclist *createDDCList() {
ddclist *newList = NULL;
newList = malloc(sizeof (ddclist));
if (!newList) {
return NULL;
}
newList->index = -1;
newList->next = NULL;
if (!newList->value) {
return NULL;
}
return newList;
}
int addDDCList(ddclist *list, char *value) {
ddclist *addList = NULL;
addList = createDDCList();
if (!addList) {
return -1;
}
if (list->index == -1) {
list->index = 0;
strcpy(list->value, value);
return 1;
}
ddclist *i, *temp;
i = list;
while (i) {
if (!i->next) {
temp = i;
}
i = i->next;
}
addList->index = (temp->index + 1);
strcpy(addList->value, value);
temp->next = addList;
return addList->index;
}
void destroyDDCList(ddclist *list){
ddclist *p=list;
while(p!=NULL){
ddclist *tmp = p->next;
free(p);
p=tmp;
}
void displayDDCList(ddclist *list) {
ddclist *l = list;
while (l) {
printf("Index:%d\nValue:%s\n\n", l->index, l->value);
l = l->next;
}
}
}