what is null in c
In C, NULL is a special macro that represents a null pointer constant —a
pointer that points to no valid object or function at all.
Quick Scoop: What is NULL in C?
NULLis a macro defined in standard headers likestdio.h,stddef.h,stdlib.h, etc.
- It expands to an implementation-defined null pointer constant, typically
0or((void*)0).
- It is used only with pointers to mean “this pointer does not point anywhere valid.”
Example:
c
#include <stdio.h>
#include <stddef.h>
int main(void) {
int *p = NULL; // p is a null pointer
if (p == NULL) {
printf("p points to nothing\n");
}
return 0;
}
Mini Section: Why NULL Exists
You use NULL to make pointer code safer and clearer.
Common uses:
-
Initialize pointers when you don’t yet have a valid address.
c int *ptr = NULL;
-
Check before dereferencing to avoid crashes like segmentation faults.
c if (ptr != NULL) { printf("%d\n", *ptr); }
-
Signal “no object” in APIs (e.g., return
NULLif a search fails, or acceptNULLwhen the caller has “nothing” to pass).c char *find_user(const char *name); // returns NULL if not found
- Mark ends in data structures , such as the last node of a linked list using
next = NULL.
Mini Section: NULL vs 0 vs “null”
In C, NULL is really just a nicer way to write the null pointer constant.
-
Writing
c int *p = NULL; int *q = 0;
is equivalent: both p and q are null pointers.
- The C standard allows the null pointer constant to be
0or((void*)0), andNULLis defined accordingly in headers.
- Many languages say “
null” generally means “no value,” but in C it specifically means a null pointer.
Mini Section: What NULL Is Not
It’s easy to mix up a few concepts when learning C pointers:
NULLis not the same as an empty string ("").NULLis not the same as integer0in a variable likeint x = 0;; that is just a number, not a pointer.
- A null pointer does not point to a valid memory location you can use , so dereferencing it (
*ptrwhenptr == NULL) is undefined behavior and can crash the program.
A small illustration:
c
int x = 0; // integer with value 0, perfectly usable
int *p = NULL; // pointer to nothing (null pointer)
// *p here would be invalid, but x is fine to read and write
Mini Section: Real-World Style Example
You’ll often see NULL in functions that work with dynamic memory:
c
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *numbers = malloc(100 * sizeof(int));
if (numbers == NULL) { // check for allocation failure
printf("Memory allocation failed.\n");
return 1;
}
// ... use numbers ...
free(numbers); // release memory
numbers = NULL; // avoid dangling pointer
return 0;
}
Here, NULL is used:
- To detect
mallocfailure (numbers == NULL). - To “reset” the pointer after
freeso it clearly no longer refers to valid memory.
TL;DR
In C, NULL is a macro that represents a null pointer constant, usually 0
or ((void*)0), and it’s used with pointers to mean “this points to nothing.”
Information gathered from public forums or data available on the internet and portrayed here.