Both stdio.h and stdlib.h are, in fact, required to define NULL, all the way back to the original ANSI C standard in 19891 (unfortunately this is a .txt file, so I can't link to a specific section; search for 4.9 INPUT/OUTPUT <stdio.h> and/or 4.10 GENERAL UTILITIES <stdlib.h>, and then scroll down a little). If either of the minimized test programs

#include <stdio.h>
void *p = NULL;

or

#include <stdlib.h>
void *p = NULL;

fails to compile to an object file, then your C implementation is buggy. (If the above test programs do not fail to compile, you're gonna need to do some delta-minimization on your actual program, and probably then track down your wiseacre cow-orker who thought it would be funny to put #undef NULL in an application header file.)

NULL is also required to be defined in several other standard headers, but its true home, as you may guess from the cross-references to section 4.1.5 to explain what NULL is supposed to be defined to, is stddef.h. A C implementation that fails to define NULL in stddef.h is egregiously buggy. Also, stddef.h is one of the very few headers that is required to be provided by a "freestanding implementation"; if you are working in an embedded environment, it's possible that they thought they could get away with leaving NULL out of stdio.h or stdlib.h, but they have no excuse whatsoever for leaving it out of stddef.h.

In the alternative, just use 0 for the null pointer constant. That's perfectly fine style as long as all your functions have prototypes. (You have to cast it to pass it correctly to a function that takes a variable number of arguments, e.g. to execl, but you have to cast NULL to pass it correctly to a function that takes a variable number of arguments, so it comes out in the wash.)


1 Footnote for historians: yes, the linked document really is the ANSI C standard, not the ISO standard with nigh-identical wording (but very different section numbering) that came out a year later. I am not aware of any copy of the 1990 edition of the ISO C standard that is available online at no charge.

Answer from zwol on Stack Overflow
Top answer
1 of 1
20

Both stdio.h and stdlib.h are, in fact, required to define NULL, all the way back to the original ANSI C standard in 19891 (unfortunately this is a .txt file, so I can't link to a specific section; search for 4.9 INPUT/OUTPUT <stdio.h> and/or 4.10 GENERAL UTILITIES <stdlib.h>, and then scroll down a little). If either of the minimized test programs

#include <stdio.h>
void *p = NULL;

or

#include <stdlib.h>
void *p = NULL;

fails to compile to an object file, then your C implementation is buggy. (If the above test programs do not fail to compile, you're gonna need to do some delta-minimization on your actual program, and probably then track down your wiseacre cow-orker who thought it would be funny to put #undef NULL in an application header file.)

NULL is also required to be defined in several other standard headers, but its true home, as you may guess from the cross-references to section 4.1.5 to explain what NULL is supposed to be defined to, is stddef.h. A C implementation that fails to define NULL in stddef.h is egregiously buggy. Also, stddef.h is one of the very few headers that is required to be provided by a "freestanding implementation"; if you are working in an embedded environment, it's possible that they thought they could get away with leaving NULL out of stdio.h or stdlib.h, but they have no excuse whatsoever for leaving it out of stddef.h.

In the alternative, just use 0 for the null pointer constant. That's perfectly fine style as long as all your functions have prototypes. (You have to cast it to pass it correctly to a function that takes a variable number of arguments, e.g. to execl, but you have to cast NULL to pass it correctly to a function that takes a variable number of arguments, so it comes out in the wash.)


1 Footnote for historians: yes, the linked document really is the ANSI C standard, not the ISO standard with nigh-identical wording (but very different section numbering) that came out a year later. I am not aware of any copy of the 1990 edition of the ISO C standard that is available online at no charge.

🌐
GeeksforGeeks
geeksforgeeks.org › c++ › null-undeclared-error-in-c-c-and-how-to-resolve-it
NULL undeclared error in C/C++ and how to resolve it - GeeksforGeeks
July 15, 2025 - The above code will show an error as "NULL undeclared Error". The reason for the NULL undeclared error is "NULL" is not a built-in constant. Why do we need NULL? When we create some pointer in our program, they are used for storing addresses. But an uninitialized pointer variable is very dangerous so that we can assign them NULL which means they are not pointing to any memory location, so our program runs smoothly and securely.
🌐
GitHub
github.com › microsoft › vscode-cpptools › issues › 2607
identifier "NULL" is undefined · Issue #2607 · microsoft/vscode-cpptools
October 4, 2018 - Issue Type: Bug I do not know from when on anytime I type NULL the reporter says this. Everything seemed to be okay before. My c_cpp_properties.json is pasted here, if required. { "configurati...
Published   Oct 04, 2018
🌐
Cprogramming
cboard.cprogramming.com › cplusplus-programming › 92384-null-not-defined.html
Null Not Defined
It doesn't have to point into memory at address value 0, but for assignments and comparisons it must behave as if it did. Any usages, such as seeing how far the offset of your array is from NULL and such, result in undefined behaviour.
🌐
Code::Blocks
forums.codeblocks.org › index.php
NULL undefined
Code::Blocks Forums » · User forums » · Help » · NULL undefined · « previous next » · Send this topic · Print · Pages: [1] 2 3 All Go Down · Send this topic · Print · Pages: [1] 2 3 All Go Up · « previous next » · Code::Blocks Forums » · User forums » ·
🌐
Quora
quora.com › What-is-the-main-difference-between-NULL-and-UNDEFINED-in-programming-Are-they-both-non-existent-values
What is the main difference between 'NULL' and 'UNDEFINED' in programming? Are they both 'non-existent values'? - Quora
Answer (1 of 9): An undefined variable does not exist at all. This error usually occurs when you attempt to access a variable before it has even been created. On the other hand, a NULL variable exists, but holds a value of zero/nothing.
🌐
TechOverflow
techoverflow.net › 2019 › 06 › 20 › how-to-fix-c-error-null-undeclared
How to fix C error 'NULL undeclared' | TechOverflow
June 19, 2019 - The reason for this error is that NULL is not defined in C itself but only in stddef.h.
Find elsewhere
🌐
Wikipedia
en.wikipedia.org › wiki › Null_pointer
Null pointer - Wikipedia
3 weeks ago - The C standard does not say that the null pointer is the same as the pointer to memory address 0, though that may be the case in practice. Dereferencing a null pointer is undefined behavior in C, and a conforming implementation is allowed to assume that any pointer that is dereferenced is not null.
🌐
Reddit
reddit.com › r/c_programming › arithmetic on null pointer -is it undefined behaviour?
r/C_Programming on Reddit: arithmetic on NULL pointer -is it undefined behaviour?
August 7, 2019 -

Considering the following code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int* p = NULL;

    printf("p is %p\n", p);
    printf("p += 1 is %p\n", p += 1);

    return 0;
}

Output using clang test.c -Wall -Wextra:

p is (nil)
p += 1 is 0x4

Output using clang test8.c -fsanitize=undefined

p is (nil)
test.c:9:29: runtime error: applying non-zero offset 4 to null pointer
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior test.c:9:29 in 
p++ is 0x4

However, since p is the NULL pointer, does p += 1 induce undefined behaviour? Is -fsanitize correct?

Top answer
1 of 5
17

The arithmetic itself is not undefined here. Look up how NULL is defined.

Edit: I stand corrected (see below)

2 of 5
12

Pointer arithmetic is undefined behavior unless kept within the bounds of an array object (or one index past the end). So this should be UB.

Edit: I'm being downvoted. Can someone explain where I've misunderstood? This is from the standard, emphasis mine.

When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integer expression. In other words, if the expression P points to the i-th element of an array object, the expressions (P)+N (equivalently, N+(P)) and(P)-N (where N has the value n) point to, respectively, the i+n-th and i−n-th elements of the array object, provided they exist. Moreover, if the expression P points to the last element of an array object, the expression (P)+1 points one past the last element of the array object, and if the expression Q points one past the last element of an array object, the expression (Q)-1 points to the last element of the array object. If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined. If the result points one past the last element of the array object, it shall not be used as the operand of a unary * operator that is evaluated.

🌐
Quora
quora.com › What-is-the-difference-between-null-undefined-and-not-defined
What is the difference between null undefined and not defined? - Quora
Answer: depends on the language. for what you are saying it sound as javascript or python. if it is that the difference is that undefined is when it was never used. and null defined is when you define it and equal it to null (and not the same) ...
🌐
Quora
quora.com › Why-is-dereferencing-null-pointer-undefined-behaviour-and-not-implementation-defined-behaviour-in-C-standards-while-there-are-architectures-that-can-store-data-at-0x0
Why is dereferencing null pointer undefined behaviour and not implementation defined behaviour in C standards while there are architectures that can store data at 0x0? - Quora
Answer (1 of 4): By making it undefined behavior, the compiler can assume that any code path that it can prove would dereference a null pointer cannot happen, and use this to optimize the code further. This allows it to remove apparently-redundant null-pointer checks and dead-code paths during o...
🌐
Handmade Network
hero.handmade.network › forums › code-discussion › t › 1292-null_define_in_c__c_differs!
NULL Define in c & c++ differs?! | Handmade Network
Note though that it implictly defined function accepts variable number of arguments, then behaviour is undefined. In your case because strstr function is not defined (string.h not included), compiler assumed it returns int. That's why it generated warning when you compare result with NULL which has "void*" type in C.
🌐
GitHub
github.com › microsoft › vscode-cpptools › issues › 11665
MacOS C language `NULL` tips `identifier "__null" is undefinedC/C++(20)` · Issue #11665 · microsoft/vscode-cpptools
November 13, 2023 - MacOS C language NULL tips identifier "__null" is undefinedC/C++(20)#11665 · Copy link · Assignees · Labels · Language Servicemore info neededThe issue report is not actionable in its current stateThe issue report is not actionable in its current state ·
Published   Nov 13, 2023
🌐
PVS-Studio
pvs-studio.com › en › blog › posts › cpp › 0306
Null Pointer Dereferencing Causes Undefined Behavior
February 16, 2015 - If a null pointer constant is converted ... unequal to a pointer to any object or function. When "an lvalue does not designate an object when it is evaluated, the behavior is undefined" (C99 6.3.2.1 "Lvalues, ......
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.

🌐
Developer Community
developercommunity.visualstudio.com › content › problem › 932792 › -null-for-linux-development-not-defined.html
__null for Linux Development not defined
Skip to main content · Microsoft · Visual Studio · Sign in · You need to enable JavaScript to run this app · Sorry this browser is no longer supported · Please use any other modern browser like 'Microsoft Edge'
🌐
Infineon Developer Community
community.infineon.com › home › resources › knowledge base articles › 'null' identifier
Identifier 'NULL' is Undefined - Infineon Developer Community
December 17, 2008 - The following is the error message for the get_cnfg.c source file compilation: *** ERROR C202 IN LINE 22 OF GET_CNFG.C: 'NULL': undefined identifier C51 COMPILATION COMPLETE. 0 WARNING(S), 1 ERROR(S). It seems that the NULL macro that these functions use as a return value, is not defined.