Greetings all,
Im getting confused about linked lists and wonder if someone can clear it up for me.
Say i have a simple linked list structured like this :
Code:
typedef struct sockets SOCKETS;
struct sockets {
int state;
int sock_id;
struct socks* next;
struct socks* prev;
};
Now a small function to populate this linked list with some inital data like :
Code:
struct sockets* populate()
{
struct sockets* head = NULL;
struct sockets* first = NULL;
head = malloc(sizeof(struct sockets));
first = malloc(sizeof(struct sockets));
head->state=1;
head->sock_id=5;
head->next=first;
head->prev=NULL;
first->state=1;
first->sock_id=6;
first->next=NULL;
first->prev=head;
return head;
}
so in my main to create this list in memory it looks like :
Code:
int main(void)
{
SOCKETS *socks;
socks = populate();
}
Ok so now I have my first node held in socks. Sorry for the simplicity of this btw as I could probably just cut to the chase but i need to make sure im doing everything as I should and make it clear what my question is in relation to how i have my lists.
Ok now if i want to delete a node from that list ive always just looped through the list until i found the key like this :
Code:
void del_node(struct sockets* first_node, int sock_id)
{
struct sockets* current = first_node;
struct sockets *tmp_next = NULL;
struct sockets *tmp_previous = NULL;
while(current != NULL) {
if(current->sock_id == sock_id) {
if(current->next == NULL) {
tmp_previous = current->previous;
tmp_previous->next = NULL;
} else {
tmp_previous = current->previous;
tmp_next = current->next;
tmp_next->previous=tmp_previous;
tmp_previous->next=tmp_next;
}
free(current);
break;
}
current = current->next;
}
}
Ok i know that is a messy for deleting but its all I could come up with while testing. Anyway heres my question (at last!) as you can see in my delete node function im just free'ing the pointer yes ? and not actually freeing the data within the struct ? as after researching this on the web I found some code by someone like this :
Code:
free(head->data); /* free mem within the list! */
free(head);
So do i have to free up all the sections in the struct aswell ?
Also ive read somewhere that after ive free a pointer its still there but has no memory allocated to it. So do i need to NULL it after I use it aswell ?
If anyone can explainwith a little example id really appreciate it.
Thanks.
mrpickle
ps. sorry for the long drawn out post !