← Back to C++ Course | Chapter 7: Pointers & References | Lesson 10 of 11

C++ Null & Void Pointer

What is a Null Pointer?

A null pointer is a pointer that deliberately does not point to any valid memory address, used to represent 'no object here yet'. Modern C++ uses the nullptr keyword for this instead of the older NULL macro, because nullptr has its own type and can't be silently confused with the integer 0.

Example: What is a Null Pointer?

cpp
#include <iostream>

int main() {
	int *ptr = nullptr;
	std::cout << "ptr points to nothing yet" << std::endl;
	return 0;
}

Checking for Null

Always check whether a pointer is null before dereferencing it, since reading from or writing to a null pointer is undefined behavior and typically crashes your program immediately with a segmentation fault. This one habit prevents one of the most common runtime bugs in pointer-heavy code.

Example: Checking for Null

cpp
#include <iostream>

int main() {
	int *ptr = nullptr;
	if (ptr != nullptr) {
		std::cout << *ptr << std::endl;
	} else {
		std::cout << "Cannot dereference: pointer is null" << std::endl;
	}
	return 0;
}

What is a Void Pointer?

A void pointer (void*) is a generic pointer that can hold the address of a variable of any data type, which makes it useful for writing type-agnostic low-level utilities. However, because the compiler no longer knows what type it points to, you cannot dereference a void pointer directly.

Example: What is a Void Pointer?

cpp
#include <iostream>

int main() {
	int num = 5;
	void *vptr = &num; // can hold the address of any type
	std::cout << "Void pointer set" << std::endl;
	return 0;
}

Casting Void Pointers

To actually read the data a void pointer refers to, you must first cast it back to its real, specific type, typically with static_cast in modern C++. Skipping this step and dereferencing the void pointer as-is won't even compile, since the compiler has no idea how many bytes to read.

Example: Casting Void Pointers

cpp
#include <iostream>

int main() {
	int num = 42;
	void *vptr = &num;
	int *intPtr = static_cast<int *>(vptr);
	std::cout << *intPtr << std::endl;
	return 0;
}

Common Pitfalls

Avoid casting a void pointer to the wrong type, since that causes the program to reinterpret memory using an incorrect size and layout, producing garbage values or corruption. Also never apply dereferencing syntax directly to a void or null pointer without first checking or casting it.

Example: Common Pitfalls

cpp
#include <iostream>

int main() {
	double num = 3.14;
	void *vptr = &num;
	int *wrongPtr = static_cast<int *>(vptr); // wrong type: misreads the bytes
	std::cout << "Casting to the wrong type corrupts the value read" << std::endl;
	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.