hello,
i am very new to C and i am reading K&R and i came
accross this code in the book. K&R says that it is
incorrect to free something after it has been freed
and gives this as an example.
for (p=head; p!= NULL; p->next)
free(p);
what's wrong with it?
There are at least two problems with this code: p->next doesn't do anything
and p is accessed after it's been freed.
Even if the first problem weren't there (i.e. the code said `p = p->next')
the second would still (possibly) kill your pprogram.
The for loop in while form looks like this:
p = head;
while (p != NULL)
{
free(p);
p = p->next;
}
perhaps it is a bit clearer now why p is accessed after the free?
To do it right, you can do it like this:
p_type p = head;
p_type last = NULL;
while (p != NULL)
{
last = p;
p = p->next;
free(last);
}
(in which p_type is some pointer type). Here, you save the old value of p to
last, get the value you want for p, and *then* free the saved, old value.
HTH
rlc
--
Jail: Just Another Interpreted Language
Just: Jail Uses Silly Terms
Join the discussion on the definition of this language at
(e-mail address removed)
http://jail-ust.sourceforge.net
(send mail to (e-mail address removed))