Re: Style question: Should one check for NULL pointers?

H. Peter Anvin
2003-07-11T20:21:22Z

Followup to: <3F0EC9C9.4090307@inet.com>
By author: Eli Carter <eli.carter@inet.com>
In newsgroup: linux.dev.kernel
> >
> > Not really needed, since a segfault will produce almost as much
> > information as a BUG_ON(). Certainly it will produce enough to let a
> > developer know that the pointer was NULL.
>
> Your first message said, "I see no reason for pure paranoia,
> particularly if it's not commented as such." A BUG_ON() call makes it
> clear that the condition should never happen. Dereferencing a NULL
> leaves the question of whether NULL is an unhandled case or invalid
> input. BUG_ON() is an explicit paranoia check, and with a bit of
> preprocessing magic, you could compile out all of those checks.
>
> So it documents invalid input conditions, allows you to eliminate the
> checks in the name of speed or your personal preference, or use them to
> help with debugging/testing.
>

... but it also bloats the code, in this case, in many ways
needlessly. You don't want to compile out all BUG_ON()'s, just the
ones that wouldn't be checked for anyway.

In fact, have a macro that explicitly tests for nullness by
dereferencing a pointer might be a good idea; on most architectures it
will be a lot cheaper than BUG_ON() (which usually requires an
explicit test), and the compiler at least has a prayer at optimizing
it out.

-hpa
--
<hpa@transmeta.com> at work, <hpa@zytor.com> in private!
If you send me mail in HTML format I will assume it's spam.
"Unix gives you enough rope to shoot yourself in the foot."
Architectures needed: ia64 m68k mips64 ppc ppc64 s390 s390x sh v850 x86-64