example5_dangling_pointer.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#include <iostream>

int main() {
    int* ptr = new int(42);  // Dynamically allocate memory

    delete ptr;  // Free the memory

    // ptr is now a dangling pointer
    // std::cout << *ptr << std::endl;  // Dereferencing ptr here would be unsafe

    ptr = nullptr;  // Prevent dangling by setting ptr to nullptr

    return 0;
}
Back to raw_pointers