← Back to C Course | Chapter 7: Pointers | Lesson 7 of 9

C Null Pointer

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?

c
#include <stdio.h>
int main() {
	int *ptr = NULL;
	printf("%d", ptr == NULL);
	return 0;
}

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

c
#include <stdio.h>
int main() {
	int *ptr = NULL;
	printf("%d", ptr == 0);
	return 0;
}

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

c
#include <stdio.h>
int main() {
	int *ptr = NULL;
	if (ptr != NULL) {
		printf("%d", *ptr);
	} else {
		printf("Cannot dereference a null pointer");
	}
	return 0;
}

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

c
#include <stdio.h>
int main() {
	int *safePtr = NULL;
	printf("%d", safePtr == NULL);
	return 0;
}

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

c
#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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.