Pointers and Memory Management
Pointer Basics
Understanding pointers and addresses
Interview: Critical C++ concept
Pointer Basics
A pointer is a variable that stores a memory address. Pointers enable direct memory manipulation, dynamic memory allocation, and efficient data structure implementation. They are one of C++'s most powerful — and dangerous — features.
Pointer Operations
- Address-of (&): Gets the address of a variable
- Dereference (*): Accesses the value at the pointed-to address
- nullptr: The null pointer constant (C++11). Always initialize pointers to nullptr if not immediately set to a valid address.
const and Pointers
The placement of const matters: const int* p — pointer to const int (can't change value, can rebind pointer). int* const p — const pointer to int (can change value, can't rebind). const int* const p — const pointer to const int (neither changeable).
Interview Corner
Q: What is the difference between a null pointer and a dangling pointer?
A: A null pointer (nullptr) explicitly points to no valid object. Dereferencing it is UB but predictably crashes (segfault). A dangling pointer points to memory that was previously valid but has since been freed or gone out of scope. Dereferencing is UB and may corrupt data silently or crash unpredictably — much harder to debug.
Common Pitfalls
- Uninitialized pointers: Declaring a pointer without initialization gives it a garbage address. Always initialize to nullptr.
- NULL vs nullptr: In C++, prefer
nullptroverNULL. NULL is typically 0 (an integer), which can cause overload resolution ambiguity.
Best Practices
- Always initialize pointers to
nullptrat declaration. - After deleting a pointer, set it to
nullptrimmediately to prevent use-after-free. - Prefer references over pointers when nullability and re-binding are not needed.