[prog] Bug!!

Akkana Peck akkana at shallowsky.com
Mon Mar 3 15:05:16 EST 2003


> On Sun, 2 Mar 2003, Sachin wrote:
> >10 bytes or pow(10,100) bytes , coudn't the free function assign a NULL
> >to the pointer to memory position it freed.Why should it be left as
> >undefined behaviour?

Jimen Ching writes:
> There isn't really much benefit except to new C programmers that might
> fall into this trap.  But once you learn it, you most likely won't
> make the same mistake.  ;-)

I wouldn't want to try to count the times I've debugged problems that
boiled down to a highly experienced programmer making this error
(dereferencing already freed memory).  I'm not sure I can count that
high. :-)  Experienced programmers can get sloppy even though they
supposedly know better, and programmers make this error all the time.

In answer to Sachin's question, free() in C is just a normal function,
which takes as argument a copy of the pointer it's going to free;
it doesn't have any way to change that pointer (it could change the
contents pointed to, but that wouldn't help).  You could make a new
routine safe_free() which takes a pointer to a pointer, or a reference
to a pointer, but if you changed the type signature of free() itself
you'd break a lot of programs which used the existing interface.

For any specific program, though, it's pretty easy to define a wrapper
around memory access routines so that you handle them safely.  Don't
feel like you're not being a "real programmer" if you do something like
this for your own code -- lots of large professional projects make this
sort of wrapper.
 
> feature of C.  The designers of the language specifically allow the
> programmer to decide what is important.  Unlike other langauges, which
> force a paradigm on its programmers, C allows you to do what is most
> convenient at the moment.  Sorry for the small rant.  ;-)

Agreed.  C gives you the power to choose.  I'm forever hearing rants
by people who hate C because it gives you the opportunity to screw up.
Yes, it does; OTOH, in other languages which supposedly make that less
likely, I can't say I've seen significantly fewer errors of this sort.
Code reviews and careful design are a better defense than relying on
language design to save you.

	...Akkana


More information about the Programming mailing list