C++ Null & Void Pointer
In this page:
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?
#include <iostream>
int main() {
int *ptr = nullptr;
std::cout << "ptr points to nothing yet" << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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?
#include <iostream>
int main() {
int num = 5;
void *vptr = # // can hold the address of any type
std::cout << "Void pointer set" << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <iostream>
int main() {
int num = 42;
void *vptr = #
int *intPtr = static_cast<int *>(vptr);
std::cout << *intPtr << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <iostream>
int main() {
double num = 3.14;
void *vptr = #
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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: