free()

Philip Herron herron.philip@googlemail.com
Sun Sep 27 14:48:00 GMT 2009


Mohsen Pahlevanzadeh wrote:
> Dear all,
> We are working on C code (not ++),So we must use free instead delete.
> I have following code:
> /////////////////////////////////
>         struct linked_list *p;
> 	p->src="10.0.0.1";
>         free(p);
>         printf ("%s",p->srcip);
> /////////I see in my output 10.0.0.1 
> My question: i drop p pinter, but see it's value, how i kill p with its
> value?
>
> Yours,
> Mohsen
>
>
>   
Hey

You use free if you have allocated it memory, so for example if you have 
a struct like:

struct list {
void *data
struct list* next;
}


You would

struct list *mylist = malloc(sizeof(struct list));
then do your assignment mylist->data= ...
mylist->next = NULL;

Then you can free mylist

The thing a good practice with free is to:

free(mylist)
mylist= NULL;

To make sure it can't be referenced again. Hope that clears a little up 
for you.

--Phil



More information about the Gcc-help mailing list