-
freeing list
ok, lets say i have a funtion that gets nodes for a link list from a malloc'ed/calloc'ed block of structs. lets also say that the function exhaust several blocks. after im finished doing whatever with the list, how do i free all the nodes. i dont think i could just traverse the list freeing each node because id end up freeing addresses that have already been freed (i think). i thought maybe i could either store the beginning address of each block allocated on a stack then traverse through that or maybe i could free the first node in the list, go down BLOCKSIZE nodes, free and repeat until end of list but im not sure which would be the best way to do it. im not even sure if thats the way it should be done.
id really appreciate it if you guys could help me out with this. thanks in advance.
-
This is the way I would take care of it:
Code:
void clear (nodePtr *front)
{
nodePtr lptr = *front; /*make lptr point to frist node in list*/
nodePtr tptr = NULL; /*tptr points to NULL*/
while(lptr != NULL) /*while the list is not empty*/
{
tptr = lptr; /*move tptr up 1 node*/
lptr = lptr->right; /*move lptr up 1 node*/
freeNode(tptr); /*free node tptr points to*/
}
*front = NULL; /*assign head to NULL, making list empty*/
}
I'm sure there are other ways to do it, but this is the easiest way I found.
-
im allocating memory for a block of structs and retrieving nodes from that. i dont think i can simply traverse the list freeing each node as i could if i had just allocated mem one node at a time. thanks anyway.