C Null Pointer
In this page:
What is a Null Pointer?
It's the conventional 'this pointer intentionally points nowhere' signal in C, used both as an initial safe default and as a sentinel value that functions like malloc() and fopen() return to indicate failure.
Example: What is a Null Pointer?
#include <stdio.h>
int main() {
int *ptr = NULL;
printf("%d", ptr == NULL);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Initializing a Null Pointer
NULL is actually just defined as the integer 0 cast to a pointer type in most implementations, so int *ptr = NULL and int *ptr = 0 are functionally equivalent, though writing NULL communicates intent more clearly to readers.
Example: Initializing a Null Pointer
#include <stdio.h>
int main() {
int *ptr = NULL;
printf("%d", ptr == 0);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Safe Pointer Checking
This is defensive programming 101 in C -- since the language has no automatic null-checking, forgetting this check is one of the most common causes of segmentation faults, especially right after a malloc() or fopen() call that might have failed.
Example: Safe Pointer Checking
#include <stdio.h>
int main() {
int *ptr = NULL;
if (ptr != NULL) {
printf("%d", *ptr);
} else {
printf("Cannot dereference a null pointer");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Null Pointer vs. Uninitialized Pointer
An uninitialized pointer is far more dangerous than a null one because it might accidentally point at valid-looking memory and appear to work, masking the bug until it corrupts something important -- always initialize pointers explicitly, even to NULL.
Example: Null Pointer vs. Uninitialized Pointer
#include <stdio.h>
int main() {
int *safePtr = NULL;
printf("%d", safePtr == NULL);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Null Pointers as Return Values
This convention lets calling code distinguish 'operation succeeded, here's your result' from 'operation failed' using a single return value, which is why checking a function's return pointer against NULL before using it is standard practice.
Example: Null Pointers as Return Values
#include <stdio.h>
int* find(int value) {
if (value != 5) {
return NULL;
}
static int found = 5;
return &found;
}
int main() {
int *result = find(3);
printf("%d", result == NULL);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: