In my experience, tests of the form if (ptr) or if (!ptr) are preferred. They do not depend on the definition of the symbol NULL. They do not expose the opportunity for the accidental assignment. And they are clear and succinct.

Edit: As SoapBox points out in a comment, they are compatible with C++ classes such as unique_ptr, shared_ptr, auto_ptr that are objects that act as pointers and which provide a conversion to bool to enable exactly this idiom. For these objects, an explicit comparison to NULL would have to invoke a conversion to pointer which may have other semantic side effects or be more expensive than the simple existence check that the bool conversion implies.

I have a preference for code that says what it means without unneeded text. if (ptr != NULL) has the same meaning as if (ptr) but at the cost of redundant specificity. The next logical thing is to write if ((ptr != NULL) == TRUE) and that way lies madness. The C language is clear that a boolean tested by if, while or the like has a specific meaning of non-zero value is true and zero is false. Redundancy does not make it clearer.

Answer from RBerteig on Stack Overflow
Top answer
1 of 6
30

In C and C++, pointers are inherently unsafe, that is, when you dereference a pointer, it is your own responsibility to make sure it points somewhere valid; this is part of what "manual memory management" is about (as opposed to the automatic memory management schemes implemented in languages like Java, PHP, or the .NET runtime, which won't allow you to create invalid references without considerable effort).

A common solution that catches many errors is to set all pointers that don't point to anything as NULL (or, in correct C++, 0), and checking for that before accessing the pointer. Specifically, it is common practice to initialize all pointers to NULL (unless you already have something to point them at when you declare them), and set them to NULL when you delete or free() them (unless they go out of scope immediately after that). Example (in C, but also valid C++):

void fill_foo(int* foo) {
    *foo = 23; // this will crash and burn if foo is NULL
}

A better version:

void fill_foo(int* foo) {
    if (!foo) { // this is the NULL check
        printf("This is wrong\n");
        return;
    }
    *foo = 23;
}

Without the null check, passing a NULL pointer into this function will cause a segfault, and there is nothing you can do - the OS will simply kill your process and maybe core-dump or pop up a crash report dialog. With the null check in place, you can perform proper error handling and recover gracefully - correct the problem yourself, abort the current operation, write a log entry, notify the user, whatever is appropriate.

2 of 6
8

The other answers pretty much covered your exact question. A null check is made to be sure that the pointer you received actually points to a valid instance of a type (objects, primitives, etc).

I'm going to add my own piece of advice here, though. Avoid null checks. :) Null checks (and other forms of Defensive Programming) clutter code up, and actually make it more error prone than other error-handling techniques.

My favorite technique when it comes to object pointers is to use the Null Object pattern. That means returning a (pointer - or even better, reference to an) empty array or list instead of null, or returning an empty string ("") instead of null, or even the string "0" (or something equivalent to "nothing" in the context) where you expect it to be parsed to an integer.

As a bonus, here's a little something you might not have known about the null pointer, which was (first formally) implemented by C.A.R. Hoare for the Algol W language in 1965.

I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.

๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-to-check-if-a-variable-is-null-in-c-cplusplus
How to check if a variable is NULL in C/C++?
In this example, we assign the pointer value to NULL and check the existence of NULL using if statement. After passing some value to pointer, it becomes not null and generate that value as result. #include<iostream> using namespace std; int main() { // Pointer initialized to NULL int* ptr = NULL; if (ptr == NULL) { cout << "The pointer is NULL."
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ null-pointer-in-c
NULL Pointer in C - GeeksforGeeks
It is a valid operation in pointer arithmetic to check whether the pointer is NULL. We just have to use isequal to operator ( == ) as shown below: ... The above equation will be true if the pointer is NULL, otherwise, it will be false.
Published ย  January 10, 2025
๐ŸŒ
Wikihow
wikihow.com โ€บ computers and electronics โ€บ software โ€บ programming โ€บ c programming languages โ€บ how to check null in c: 7 steps (with pictures) - wikihow
How to Check Null in C: 7 Steps (with Pictures) - wikiHow
June 9, 2025 - It will return FALSE if ptr is NULL, or if ptr is 0. The distinction doesn't matter in many cases, but be aware that these are not identical in all architectures.[1] X Research source ยท The reverse of this is if (!ptr), which will return TRUE if ptr is FALSE. ... Set a pointer before checking for NULL.
๐ŸŒ
Cprogramming
cboard.cprogramming.com โ€บ c-programming โ€บ 162676-check-if-variable-null.html
Check if a variable is null
Simple question, I have a variable ... ... To answer your question generically (and hopefully clearly enough): C doesn't have the general concept of null meaning a/any variable is unset or invalid....
๐ŸŒ
W3Schools
w3schools.com โ€บ c โ€บ c_null.php
C NULL
For example, fopen() returns NULL if a file cannot be opened, and malloc() returns NULL if memory allocation fails. We can check for this using an if statement, and print an error message if something goes wrong.
Find elsewhere
๐ŸŒ
Quora
quora.com โ€บ How-do-I-check-if-a-pointer-is-null-in-C
How to check if a pointer is null in C - Quora
Answer (1 of 5): From the top: #ifndef NULL #define NULL (*)(0) #endif /**********************************/ /* we just have set a value for a */ /* NULL pointer. From ancient times */ /* this points to physical and or */ /* logical address 0 *************/ /******************************...
๐ŸŒ
Unstop
unstop.com โ€บ home โ€บ blog โ€บ null pointer in c | a detailed explanation with examples
Null Pointer In C | A Detailed Explanation With Examples // Unstop
May 3, 2024 - The first pointer intPtr is an integer type pointer, and floatPtr is a floating-point type pointer. We initialize them both to NULL, which indicates that neither pointer currently points to any valid memory location. We then use two separate if-statements to check if each pointer is equal to NULL, using the relational equality operator.
๐ŸŒ
Reddit
reddit.com โ€บ r/c_programming โ€บ c langauge and checking for null
r/C_Programming on Reddit: C Langauge and Checking For NULL
November 17, 2014 -

I'm new to C and would like to know best practices for NULL checking.

In languages like Javascript I check for null/undefined all the time.

For building a software framework:

  • How much NULL checking is enough in a C program.

  • How about assertions?

  • Can you go too far?

  • What are best practices in C?

like:

typedef void (*freeFuncPtr)(Mechanism*);

void mechFree(Mechanism* d) {
  if (d) {
    assert(d->class);
    assert(d->class->delete);
    freeFuncPtr funct = mech->class->delete;
(funct)(d);
    free(d);
  }
}

mechFree is used by "our user" (the developer) so they could accidentally send NULL to this function. However, we (the framework builders) implemented d->class and d->class->delete so assert seems ok.

I know some of this is programming style and context is also really important but some best known C programming practice hints would be really helpful.

Edit: fixed coding bug

๐ŸŒ
WsCube Tech
wscubetech.com โ€บ resources โ€บ c-programming โ€บ null-pointer
Null Pointer in C Language (Uses, Best Practices, Examples)
August 29, 2025 - Learn about the null pointer in C language, including its syntax, uses, how to check it, best practices, examples, and more. Read now!
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ cprogramming โ€บ c_null_pointer.htm
NULL Pointer in C
It is always recommended to check whether a pointer is NULL before dereferencing it to fetch the value of its target variable. ... #include <stdio.h> int main(){ int *ptr = NULL; // null pointer if (ptr == NULL) { printf("Pointer is a NULL pointer"); } else { printf("Value stored in the address referred by the pointer: %d", *ptr); } return 0; } When you run this code, it will produce the following output โˆ’
๐ŸŒ
Quora
quora.com โ€บ How-do-you-know-if-your-pointer-is-null-or-not-in-C
How to know if your pointer is null or not in C++ - Quora
Answer (1 of 2): A programmer can know if a pointer is NULL by explicitly comparing it to the value defined for it. Never, never, *NEVER* assume the value chosen for NULL is 0. NULL may be 0 in every C++ program you ever write.