71

I always think simply if(p != NULL){..} will do the job. But after reading this Stack Overflow question, it seems not.

So what's the canonical way to check for NULL pointers after absorbing all discussion in that question which says NULL pointers can have non-zero value?

18
  • 4
    That's not c...it's a c++ thread... personally, I'd go with: if(p) {...} Commented May 31, 2011 at 9:54
  • 4
    You are worrying too much - your code is fine, even in C++. That discussion was between some language lawyers - it's kind of the "how many angels can dance on a head of pin" stuff. Commented May 31, 2011 at 9:55
  • 4
    @cpuer No they won't because they are not using the internal rep - your code is fine! It's the way ALL C code and ALL C++ code is written - that thread was an abstract intellectual discussion about the wording of the C++ standard. You get a lot of that on the C++ tags. Commented May 31, 2011 at 10:03
  • 2
    @cpuer: in C even if (p != 0) will "work" when the internal representation is not all bits zero. Commented May 31, 2011 at 10:07
  • 3
    To keep the issues clearer: NULL is a macro, defined in <stddef.h> (and some other headers). NULL is not a null pointer; it is required to be defined as a "null pointer constant" (which in C++, cannot be a pointer, and in C, traditionally is not a pointer). There are three separate concepts which must be dealt with: NULL, a null pointer, and a null pointer constant. And how a null pointer is physically represented (its bit pattern) is completely independent of the other two. Commented May 31, 2011 at 17:34

9 Answers 9

98

I always think simply if(p != NULL){..} will do the job.

It will.

Sign up to request clarification or add additional context in comments.

15 Comments

This style is considered better than if(p), because the expression inside an if-statement should be a boolean one, and "p" in this case is a pointer, not a bool. It is considered safer and better practice to explicitly check against zero with == or != (MISRA-C:2004 13.2).
@Lundin: the condition inside an if statement only needs to be convertible to a boolean; in that context p is equivalent to p != NULL, and it's purely a matter of aesthetics which you choose. Neither is safer or "better practice" than the other.
@Mike Seymour I'm rather against if (p) because I still have to stop and think about it. As you say, it's probably a question of experience; I've only been using C and C++ for 30 years, so no doubt it will come to me in time. (Seriously, it may be a question of another experience; I used Pascal and Modula-2 extensively before starting with C, and had already grown used to strict typing. I've never felt comfortable with C's looseness here, with implicit conversions all over the place.)
@James: OK, I was wrong to say that experienced programmers won't find either form unclear. That surprises me, but I can't argue with evidence.
@Lundin: In C, yes. In C++, (void*)0 is not a valid definition for NULL; it must be convertible to any pointer type, and C++ does not allow implicit conversions from void* to other pointer types. So NULL must be defined as a zero-valued literal of integer type, and comparing that to another numeric type will not give a warning. (C++0x will sort this out by introducing nullptr, of a type that's convertible to pointer types but not numeric types, but until then we just have to muddle through as best we can).
|
44

First, to be 100% clear, there is no difference between C and C++ here. And second, the Stack Overflow question you cite doesn't talk about null pointers; it introduces invalid pointers; pointers which, at least as far as the standard is concerned, cause undefined behavior just by trying to compare them. There is no way to test in general whether a pointer is valid.

In the end, there are three widespread ways to check for a null pointer:

if ( p != NULL ) ...

if ( p != 0 ) ...

if ( p ) ...

All work, regardless of the representation of a null pointer on the machine. And all, in some way or another, are misleading; which one you choose is a question of choosing the least bad. Formally, the first two are indentical for the compiler; the constant NULL or 0 is converted to a null pointer of the type of p, and the results of the conversion are compared to p. Regardless of the representation of a null pointer.

The third is slightly different: p is implicitly converted to bool. But the implicit conversion is defined as the results of p != 0, so you end up with the same thing. (Which means that there's really no valid argument for using the third style—it obfuscates with an implicit conversion, without any offsetting benefit.)

Which one of the first two you prefer is largely a matter of style, perhaps partially dictated by your programming style elsewhere: depending on the idiom involved, one of the lies will be more bothersome than the other. If it were only a question of comparison, I think most people would favor NULL, but in something like f( NULL ), the overload which will be chosen is f( int ), and not an overload with a pointer. Similarly, if f is a function template, f( NULL ) will instantiate the template on int. (Of course, some compilers, like g++, will generate a warning if NULL is used in a non-pointer context; if you use g++, you really should use NULL.)

In C++11, of course, the preferred idiom is:

if ( p != nullptr ) ...

, which avoids most of the problems with the other solutions. (But it is not C-compatible:-).)

10 Comments

@James Kanze,I don't think there's such implicit conversion as void *p = main;if(p == 0x4004e3)printf("1\n"); prints 1(here 0x4004e3 should be replaced with the actual address of main). That said,a pointer can be used to compare with an integer,and no conversion is involved.
@compile-fan Of course there's no such implicit conversion. main has, in fact, a very special type; I don't think that there's any way to get its address, at least in C++, and if you could, there's nothing you could do with it. But in general, there's no implicit conversion of one pointer type to another, except for the special case that any data pointer can be converted to a void* with acceptable cv qualifiers. If the code you cite compiles, the compiler is broken.
@James Kanze ,it compiles in C,I think should also compile in c++.You can just put the code into the body of int main(int argc,char *argv[]){...}.
Warning is given,but it compiles anyway.
@vompile-fan It is not legal C, nor legal C++. In C, you can take the address of main, provided a declaration of main is visible; in C++, I'm not sure. In neither language, however, is there an implicit conversion of a pointer to function to void*, and in neither can you compare a pointer with an integer, other than a null pointer constant. The first is often accepted (with or without warning), for historical reasons; a compiler which accepts the second, however, is seriously broken.
|
10

The compiler must provide a consistent type system, and provide a set of standard conversions. Neither the integer value 0 nor the NULL pointer need to be represented by all-zero bits, but the compiler must take care of converting the "0" token in the input file to the correct representation for integer zero, and the cast to pointer type must convert from integer to pointer representation.

The implication of this is that

void *p;
memset(&p, 0, sizeof p);
if(p) { ... }

is not guaranteed to behave the same on all target systems, as you are making an assumption about the bit pattern here.

As an example, I have an embedded platform that has no memory protection, and keeps the interrupt vectors at address 0, so by convention, integers and pointers are XORed with 0x2000000 when converted, which leaves (void *)0 pointing at an address that generates a bus error when dereferenced, however testing the pointer with an if statement will return it to integer representation first, which is then all-zeros.

4 Comments

OK,so let's regard null pointer const(0,void *0,NULL) as a special case,what about when comparing a pointer with a non-zero integer?Please see my updated question above:)
You still need to convert either value so it can be compared, there is no direct comparison operator. In my compiler that means, that either the left or the right hand side is XOR'd before comparison, which makes the entire thing consistent again.
That's sensible, but it's not required. Assigning 0 to an int, then explicitly converting that int to a pointer is allowed to give different results than the implicit conversion of the constant 0 to a pointer.
@James Kanze As someone who thinks of the sentence "A diagnostic is not required" as a challenge, I am intrigued by the idea. There goes tonight's Minecraft session.
7

The actual representation of a null pointer is irrelevant here. An integer literal with value zero (including 0 and any valid definition of NULL) can be converted to any pointer type, giving a null pointer, whatever the actual representation. So p != NULL, p != 0 and p are all valid tests for a non-null pointer.

You might run into problems with non-zero representations of the null pointer if you wrote something twisted like p != reinterpret_cast<void*>(0), so don't do that.

Although I've just noticed that your question is tagged C as well as C++. My answer refers to C++, and other languages may be different. Which language are you using?

2 Comments

what about when comparing a pointer with a non-zero integer?Please see my updated question above:)
@compile-fan: comparison with a non-zero integer shouldn't compile, since a pointer can't be compared directly to an integer, and only a zero-valued integer literal can be implicitly converted to a (null) pointer. You can force it to compile with a dodgy cast, but then the behaviour is undefined. (Again, I'm answering for C++, but I'm fairly sure the answer is the same in C).
6

Apparently the thread you refer is about C++.

In C your snippet will always work. I like the simpler if (p) { /* ... */ }.

6 Comments

@pmg,I added c++ tag,so my purpose is to conclude a way to check null pointers that'll work for both c/c++
@cpuer Do what you are doing! Really, there is no problem here!
Checking for null pointers is nothing compared to the problems you will face with multi-language source files. I suggest you stick to one language per source file. ;)
@pmg,sure,I'll never mix two languages in a single file:)
So, when it's C, use if (p) (if (p != NULL), if (p != 0)) or if (!p) (if (p == NULL), if (p == 0)); when it's C++, use the C++ idiom (I have no idea what it is).
|
3

The representation of pointers is irrelevant to comparing them, since all comparisons in C take place as values not representations. The only way to compare the representation would be something hideous like:

static const char ptr_rep[sizeof ptr] = { 0 };
if (!memcmp(&ptr, ptr_rep, sizeof ptr)) ...

6 Comments

@R..,maybe you can lay down more words on this:) It seems to me should be !memcmp(ptr, ptr_rep, sizeof ptr) at least...
No, my version is correct. You want to compare the representation of ptr, not the representation of what it points to, so you need the address of the variable ptr.
@R..,what about when you compare a pointer with a non-zero integer, does implicit convertion happen? Or is it like @James Kanze said,a compiler that accepts compare a pointer with an integer, other than a null pointer constant,is seriously broken ?
Pointers cannot be compared against integers without an explicit cast, which has implementation-defined behavior. The integer constant expression zero (but not non-integer-constant-expression zeros) just happens to be special; the integer constant expression 0 becomes a null pointer when needed. An interesting consequence is that void *dummy = sizeof(short)-2; makes a compile-time assertion that sizeof(short)==2 (it's only valid C if the expression evaluates to 0).
if (p != 0x567) is not valid C and will not compile. What you mean is if (p != (void *)0x567), but this has implementation-defined behavior and is not necessarily the same as comparing the representation.
|
2

Well, this question was asked and answered way back in 2011, but there is nullptrin C++11. That's all I'm using currently.

You can read more from Stack Overflow and also from this article.

2 Comments

Question did not exclude C++11. You can learn more from the above two links.
I don't know if you are just trying to piss people off or anything. The links I provided gives plenty of explanation. There's no use - and would be bad- to be copy-pasting the contents of the links here. As his question has already been answered in stackoverlow. I provided the solution by saying 'you can use nullptr in C++11' while giving the links for elaboration. If I wrote if(p == nullptr) {}. in the answer as well, it would just be an insult to the OP. nullptr IS the canonical way as included by the official C++ standard. Your lack of decency will not waste any more of my time.
1

if(p != NULL) is a safe and portable way to check if a pointer is NULL.

Section 7.19 of the C11 standard describes definitions contained in stddef.h, including NULL. The relevant parts are as follows:

1 The header <stddef.h> defines the following macros and declares the following types. Some are also defined in other headers, as noted in their respective subclauses.

...

3 The macros are

NULL

which expands to an implementation-defined null pointer constant; ...

This only states that NULL is implementation defined. It doesn't say that it has to have all bits 0.

Also, section 6.2.3.2p3 defines null pointers and null pointer constants:

An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

While the above states that both 0 (when converted to a pointer) and (void *)0 constitute a null pointer constant, it doesn't imply that the resulting pointer has all bits 0. There are several other examples in the standard where converting a value from one type to another doesn't necessarily means the representation is the same.

This also states that a null pointer constant will compare unequal to any object or function. Paragraph 4 of this section also states:

Conversion of a null pointer to another pointer type yields a null pointer of that type. Any two null pointers shall compare equal.

So that if p is a null pointer then it must compare equal to any null pointer including NULL, in which case p != NULL would evaluate to false. Conversely, if p points to an object or function then it must compare unequal to any null pointer in which case p != NULL would evaluate to true.

Again, note that nothing here makes any assumptions about what representation a null pointer would have.

Comments

0

Nowadays, you can use the is null and is not null constructs. These read clearly.

if (ptr is null)
    throw new ArgumentNullException();

if (ptr is not null)
{
    // do something
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.