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.

Discussions

checking for null pointer
Do you know and trust the code that calls the function to be able to guarantee that a NULL value will never be passed in? Do you trust that this will stay true in the future as the code is changed? If you're wrong is it okay if the whole program crashes? Checking generally should be the default and only omitted if you're really really sure you don't need them. It's easier if you just put them in and then don't have to think about it. More on reddit.com
🌐 r/C_Programming
24
12
July 19, 2024
C Langauge and Checking For NULL
As with many things, the answer is "it depends". If you're hacking together a quick tool that you'll use once and throw away, you can probably omit most of them and not care. It only needs to work once, right? If you're writing software to run on satellites or Mars landers, you better do everything you can to make sure it's not going to crash. Check for NULL on every parameter in every function, even if you think it's only going to be called from someplace that's already checked it. Check every pointer before dereferencing it. I write software for an embedded platform, so we have to be kind of strict about it. Unlike a PC, if we dereference NULL, we'll get a nonmaskable interrupt, and we can't just kill the "application" to handle it. Our only recourse is to reboot the whole device. Would you like it if your desk phone rebooted? Probably not. So we have to check for NULL, and not just with asserts but by explicitly coding alternative behavior in case a NULL pointer is found. More on reddit.com
🌐 r/C_Programming
25
10
November 17, 2014
People also ask

How to check if a pointer is NULL in C?
You can check whether a pointer is NULL by using an if condition before accessing it to ensure it points to valid memory. For example, if (ptr == NULL) checks whether the pointer is empty before using it.
🌐
wscubetech.com
wscubetech.com › resources › c-programming › null-pointer
Null Pointer in C Language (Uses, Best Practices, Examples)
What is a null pointer in C?
A null pointer in C is a pointer that does not point to any valid memory location and is assigned the value NULL.
🌐
wscubetech.com
wscubetech.com › resources › c-programming › null-pointer
Null Pointer in C Language (Uses, Best Practices, Examples)
What is the value of a null pointer in C?
The value is NULL, which is usually defined as ((void *)0) or 0, depending on the system.
🌐
wscubetech.com
wscubetech.com › resources › c-programming › null-pointer
Null Pointer in C Language (Uses, Best Practices, Examples)
🌐
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 - Although many programmers treat it as equal to 0, this is a simplification that can trip you up later on. It's best to check your pointers against NULL directly, and use 0 in other contexts.
🌐
GeeksforGeeks
geeksforgeeks.org › c language › null-pointer-in-c
NULL Pointer in C - GeeksforGeeks
Following are some most common uses of the NULL pointer in C: To initialize a pointer variable when that pointer variable hasn't been assigned any valid memory address yet. To check for a null pointer before accessing any pointer variable.
Published   January 10, 2025
🌐
Cprogramming
cboard.cprogramming.com › c-programming › 162676-check-if-variable-null.html
Check if a variable is null
April 18, 2014 - 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....
Find elsewhere
🌐
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.
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-check-if-a-variable-is-null-in-c-cplusplus
How to check if a variable is NULL in C/C++?
March 15, 2026 - Always check for NULL before dereferencing a pointer to avoid segmentation faults. Functions like malloc(), fopen(), and others return NULL on failure. Use == NULL or != NULL for explicit comparison, or simply !ptr for checking if null.
🌐
Unstop
unstop.com › home › blog › null pointer in c | a detailed explanation with examples
Null Pointer In C | A Detailed Explanation With Examples
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.
🌐
WsCube Tech
wscubetech.com › resources › c-programming › null-pointer
Null Pointer in C Language (Uses, Best Practices, Examples)
March 18, 2026 - Learn in this tutorial about the null pointer in C, including its syntax, uses, how to check it, best practices, and examples to write efficient programs.
🌐
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

🌐
Memory Barrier
membarrier.wordpress.com › 2020 › 11 › 08 › stop-checking-for-null-pointers
Stop checking for NULL pointers! | Memory Barrier
January 5, 2021 - So what makes NULL special in this case? Some people who argue for NULL checks contend that it is a common-enough mistake to deserve special handling. It is true that static variables in C are initialized to 0 if no other value is given, and that malloc() returns NULL if it fails (and most programmers do not check for malloc() failures).
🌐
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 *************/ /******************************...
🌐
Scaler
scaler.com › home › topics › what is null pointer in c?
What is Null Pointer in C? - Scaler Topics
September 4, 2023 - The built-in malloc() method is used to allocate memory in the example below. If the malloc() function fails to allocate memory, the result is a NULL pointer. As an outcome, a condition to check whether the value of a pointer is null or not must be included; if the value of a pointer is not null, memory must be allocated.
🌐
Cprogramming.com
cprogramming.com › tips › tip › always-check-for-null-in-c
Always check for NULL (in C) - Cprogramming.com
How to begin Get the book · C tutorial C++ tutorial Game programming Graphics programming Algorithms More tutorials
🌐
TutorialsPoint
tutorialspoint.com › cprogramming › c_null_pointer.htm
NULL Pointer in C
When you run this code, it will produce the following output − · The value of pointer is 0. Following are some of the applications of a NULL pointer − · To initialize a pointer variable when that pointer variable isn't assigned any valid memory address yet. To pass a null pointer to a function argument when we don't want to pass any valid memory address. To check for a null pointer before accessing any pointer variable so that we can perform error handling in pointer-related code.
🌐
PVS-Studio
pvs-studio.com › en › blog › posts › cpp › 1100
Shall we check pointer for NULL before calling free function?
February 6, 2024 - The function accepts (and does nothing with) the null pointer to reduce the amount of special-casing · If the pointer is non-null but still invalid, then the check doesn't protect against anything.
Top answer
1 of 9
17

Invalid null pointers can either be caused by programmer error or by runtime error. Runtime errors are something a programmer can't fix, like a malloc failing due to low memory or the network dropping a packet or the user entering something stupid. Programmer errors are caused by a programmer using the function incorrectly.

The general rule of thumb I've seen is that runtime errors should always be checked, but programmer errors don't have to be checked every time. Let's say some idiot programmer directly called graph_get_current_column_color(0). It will segfault the first time it's called, but once you fix it, the fix is compiled in permanently. No need to check every single time it's run.

Sometimes, especially in third party libraries, you'll see an assert to check for the programmer errors instead of an if statement. That allows you to compile in the checks during development, and leave them out in production code. I've also occasionally seen gratuitous checks where the source of the potential programmer error is far removed from the symptom.

Obviously, you can always find someone more pedantic, but most C programmers I know favor less cluttered code over code that is marginally safer. And "safer" is a subjective term. A blatant segfault during development is preferable to a subtle corruption error in the field.

2 of 9
13

Kernighan & Plauger, in "Software Tools", wrote that they would check everything, and, for conditions that they believed could in fact never happen, they would abort with an error message "Can't happen".

They report being rapidly humbled by the number of times they saw "Can't happen" come out on their terminals.

You should ALWAYS check the pointer for NULL before you (attempt to) dereference it. ALWAYS. The amount of code you duplicate checking for NULLs that don't happen, and the processor cycles you "waste", will be more than paid for by the number of crashes you don't have to debug from nothing more than a crash dump - if you're that lucky.

If the pointer is invariant inside a loop, it suffices to check it outside the loop, but you should then "copy" it into a scope-limited local variable, for use by the loop, that adds the appropriate const decorations. In this case, you MUST ensure that every function called from the loop body includes the necessary const decorations on the prototypes, ALL THE WAY DOWN. If you don't, or can't (because of e.g. a vendor package or an obstinate coworker), then you must check it for NULL EVERY TIME IT COULD BE MODIFIED, because sure as COL Murphy was an incurable optimist, someone IS going to zap it when you aren't looking.

If you are inside a function, and the pointer is supposed to be non-NULL coming in, you should verify it.

If you are receiving it from a function, and it is supposed to be non-NULL coming out, you should verify it. malloc() is particularly notorious for this. (Nortel Networks, now defunct, had a hard-and-fast written coding standard about this. I got to debug a crash at one point, that I traced back to malloc() returning a NULL pointer and the idiot coder not bothering to check it before he wrote to it, because he just KNEW he had plenty of memory... I said some very nasty things when I finally found it.)

🌐
Thomas Claudius Huber
thomasclaudiushuber.com › 2020 › 03 › 12 › c-different-ways-to-check-for-null
C#: Different ways to Check for Null – Thomas Claudius Huber
Hi Thanks for the article. I have seen null == name been used too, Is it somehow better than any other cases December 15, 2022 at 5:40 am ... That’s OK too, and it’s the original syntax to check for null in C# (and still valid!) December 16, 2022 at 10:38 am