effect of free()
Alan J Rosenthal
flaps at dgp.toronto.edu
Tue Aug 15 13:35:44 AEST 1989
Perhaps I can shed a little light on this discussion (not that it's been
completely void of light so far, far from it).
The original code looked something like this:
char *a, *b, *malloc();
a = malloc(...);
b = a;
free(a);
... b ...
The poster asked if free(a) freed b. Seemed to be thinking of a lisp-like
language where objects don't go away until the last pointer to them does.
I think the following is a good way to think of it, given that pointers are
quite abstract objects. Suppose you tell me your work phone number, and I
write it down. I go home and copy it into my address book. I use the copy in
my address book when I telephone you, but for some reason leave the piece of
paper you wrote your number on in my wallet. A month later I see you and you
say "the number's been changed, here give me that piece of paper" and you
correct it on the piece of paper. But I go home and the old number's written
down in my address book, not crossed off or altered. Obviously I can't phone
you using the number you've crossed out, but can I phone you using my previous
copy of the number, which was copied when the number was still valid?
Copying a pointer doesn't copy what it points to, any more than copying the
phone number duplicates the phone it's the number of.
ajr
p.s. of course, as well, since C is call-by-value, "free(a)" can't change the
value of `a' either, but I think the original poster understood that.
More information about the Comp.lang.c
mailing list