C++ Pointers, References, nullptr & Memory Safety Masterclass

โšก Modern C++ (C++17 / C++20 / C++23) ๐ŸŸข Lesson 8 ๐Ÿ“‚ Phase 08: Pointers & Memory Safety ๐Ÿ“… 2026 Master Edition
๐Ÿ“Œ Covered in this in-depth guide: Address-of & Dereferencing ยท nullptr vs NULL ยท References vs Pointers ยท Pointer Arithmetic ยท Ownership Guidelines ยท Smart Pointers Intro

Welcome to Phase 8 (Chapter 8): C++ Pointers, References, nullptr & Memory Safety Masterclass! Memory management lies at the core of C++. In Modern C++, raw pointers are used only for non-owning access, nullptr replaces NULL, and resource ownership is managed using smart pointers or RAII.

1Modern C++ Pointer Ownership Rules

Core Guidelines for Modern C++ Pointers:

1. Use nullptr: Always initialize pointers to nullptr (C++11) instead of NULL or 0.

2. Avoid raw new / delete: Use smart pointers (std::unique_ptr, std::shared_ptr) or containers for resource ownership.

3. Raw pointers for Non-Owning View: Raw pointers (T*) should only be used to inspect or pass memory owned elsewhere.

4. Prefer References (T&): If a parameter cannot be null, pass by reference (T&) rather than pointer (T*).

2Code Demonstration: Pointers & References
C++ โ€” Pointers, References & nullptrโ–ถ Run Code in C++ Compiler
#include <iostream>

int main() {
    int number{42};
    int* ptr{&number};   // Pointer holding address of number
    int& ref{number};    // Reference alias for number

    std::cout << "Value of number: " << number << "\n";
    std::cout << "Address (&number): " << &number << "\n";
    std::cout << "Pointer value (ptr): " << ptr << "\n";
    std::cout << "Dereferenced (*ptr): " << *ptr << "\n";
    std::cout << "Reference (ref): " << ref << "\n\n";

    // Modifying through reference
    ref = 100;
    std::cout << "After ref = 100, number is: " << number << "\n";

    // C++11 nullptr check
    int* nullPtr{nullptr};
    if (nullPtr == nullptr) {
        std::cout << "nullPtr is safely checked against nullptr!\n";
    }
    return 0;
}
3Technical FAQs

Q1: What is the difference between a pointer and a reference in C++?

Pointers hold memory addresses, can be nullptr, and can be reassigned. References are non-null aliases that must be initialized upon declaration and cannot be reassigned.

Q2: Why was nullptr introduced in C++11 to replace NULL?

NULL is macro constant 0 (an integer), which caused function overloading ambiguity between f(int) and f(char*). nullptr is a dedicated pointer type (std::nullptr_t).

Q3: What is a dangling pointer?

A pointer referencing memory that has already been deallocated or gone out of scope. Accessing a dangling pointer causes undefined behavior.

Q4: What is pointer arithmetic?

Adding/subtracting integers to a pointer moves its address by multiples of sizeof(T) bytes.

Q5: What is std::unique_ptr?

A smart pointer (C++11) that owns a dynamically allocated object exclusively and automatically deallocates it when going out of scope.