Unix Programming - question on free function

This is Interesting: Free IT Magazines  
Home > Archive > Unix Programming > March 2006 > question on free function





You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

Author question on free function
jamesonang@gmail.com

2006-03-12, 5:51 pm

i have some doubts on free function when i write a linked list.

here are my data structure:

typedef struct listnode {
other_datatype *data;
struct listnode *next ;

} listnode_t ;

listnode_t *listhead;
....
....

I write a freelist ( ) function to free memory when linked list is not
used. I want to free all memory , including the linked list self and
the data pointed by listnode_t.data.

1 void freelist () {
2 listnode_t ptr =null ;
3 while( listhead!=null ) {
4 ptr = listhead;
5 listhead = listhead->next ;
6 free( ptr->data ) ;
7 free( ptr ) ;
8 }
9 }

why above code could not work? when i remove the line 6 , compiler
report no error.
but the memory of ptr->data was freed ? why?

thanks for help!

Nils O. Selåsdal

2006-03-12, 5:51 pm

jamesonang@gmail.com wrote:
> i have some doubts on free function when i write a linked list.
>
> here are my data structure:
>
> typedef struct listnode {
> other_datatype *data;
> struct listnode *next ;
>
> } listnode_t ;
>
> listnode_t *listhead;
> ...
> ...
>
> I write a freelist ( ) function to free memory when linked list is not
> used. I want to free all memory , including the linked list self and
> the data pointed by listnode_t.data.
>
> 1 void freelist () {
> 2 listnode_t ptr =null ;

given the above declarations, the above should read
listnode_t *ptr = NULL;

Please post actual code.

> 3 while( listhead!=null ) {
> 4 ptr = listhead;
> 5 listhead = listhead->next ;
> 6 free( ptr->data ) ;
> 7 free( ptr ) ;
> 8 }
> 9 }
>
> why above code could not work? when i remove the line 6 , compiler
> report no error.

Not that easy to guess. It should work.
What is the exact error the compiler tells you ?

> but the memory of ptr->data was freed ? why?


What ?


> thanks for help!
>

Sponsored Links






Free braindumps | Software forum | Database administration forum

Copyright 2003 - 2008 webservertalk.com