Pointer if test for for NULL

Peter Dufault dufault at hda.com
Thu Apr 29 10:20:44 UTC 2010


On Apr 28, 2010, at 9:39 , Chris Johns wrote:

> The Austin Group (Open Group) has been having a discussion about NULL meaning all bits 0 [0][1]. For example:
> 
> struct s* p;
> p = malloc (sizeof (struct s));
> if (p)
>   memset (p, 0, sizeof (*p));
> 
> The issue raised is "If 'struct s' contains a pointer is the pointer initialised to NULL correctly ?". This is not what I wish to discuss.
> 
> Considering this I am wondering if the 'if (p)' code is strictly valid ?
> 
> Does this code also imply false happens if NULL is all bits 0 ?
> 
> Should this code be changed to:
> 
> if (p != NULL)
> 
> I am guilty of coding the if's this way and I am wondering if this should be changed.
> 

I briefly looked at what they're talking about - architectures where NULL is not all-bits-zero and what happens in memset(..,0,..) in a structure with pointers in it.

I think there's no point in changing it. There is so much code that would break if this idiom didn't work it seems pointless, and if prototypes are in scope this has to work even on architectures where NULL isn't all-bits-zero, and one important goal of warning cleanup is to get prototypes in scope for C.

I tried to decide if on a "NULL not all-bits-zero" architecture you could come up with devious prototypes for malloc() to make your example not work.  I guess that's your basic question.  If the NULL bit pattern is actually 0xffffffff and you prototype malloc() to be uint8_t and you ignore all the warnings you're going to get when malloc() returns NULL, then p would wind up being 0x000000ff, and so "if (p)" would succeed.  I don't think this is an argument for removing "if (p) {".  If the style guide for a code base says "use if (p != NULL) {" then by all means change it in *that code base only*, leave it alone in external code.

Peter
-----------------
Peter Dufault
HD Associates, Inc.      Software and System Engineering




More information about the users mailing list