LWN.net Logo

C and C++ could have non_nullable pointers, easily

C and C++ could have non_nullable pointers, easily

Posted Aug 21, 2009 8:00 UTC (Fri) by hppnq (guest, #14462)
In reply to: C and C++ could have non_nullable pointers, easily by njs
Parent article: Null pointers, one month later

Once it's a non-null pointer, it becomes legal to dereference.

This assumes that pointers do not change, which is only true in the trivial cases. If you want to be completely safe, your only option is to always check, right before using it, that a pointer is not NULL.

And then, by the way, you still have to worry about what will happen it turns out to be pointing to 0x1. ;-)


(Log in to post comments)

C and C++ could have non_nullable pointers, easily

Posted Aug 21, 2009 22:53 UTC (Fri) by nix (subscriber, #2304) [Link]

I've maintained code that actually went so far as to do this:
struct blah *foo (...)
{
    if (error_1)
        return NULL;

    if (error_2)
        return (struct blah *)1;

    if (error 3)
        return (struct blah *)2;

    /* repeat for ten or so errors */

    return /* a real struct blah */;
}
After I'd finished being sick into the keyboard I got a new keyboard and fixed it so it didn't do that anymore.

C and C++ could have non_nullable pointers, easily

Posted Aug 21, 2009 23:40 UTC (Fri) by corbet (editor, #1) [Link]

Ever seen the kernel ERR_PTR() macro? :)

C and C++ could have non_nullable pointers, easily

Posted Aug 22, 2009 0:34 UTC (Sat) by nix (subscriber, #2304) [Link]

Ew. I wish you hadn't drawn my attention to that :)

... but ERR_PTR() has a somewhat comprehensible reason to exist. The thing
I'm discussing had only half a dozen callers, and half of them ignored the
fact that it might return an error and just blindly dereferenced anyway
(but for all I know the same is true of ERR_PTR()s users).

C and C++ could have non_nullable pointers, easily

Posted Sep 9, 2009 6:59 UTC (Wed) by cmccabe (guest, #60281) [Link]

I actually don't see what the big deal is with ERR_PTR and friends.

In higher level languages like OCaml, Java, etc., when you encounter an unrecoverable error in a function, you throw an exception. Then the function has no return value-- control just passes directly to the relevant catch() block.

ERR_PTR is the same thing. Normally, the function would return a foo pointer, but an unrecoverable error happened. So you get an error code instead. As a bonus, if you forget to check for the error code, you get a guaranteed crash (well, if some bonehead hasn't allowed the page starting at address 0 to be mapped). I say "bonus" because the alternative is usually a nondeterministic crash.

Copyright © 2013, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds