example2_dynamic_memory_allocation.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 an integer and initialize it to 42

    std::cout << "Value pointed to by ptr: " << *ptr << std::endl;

    delete ptr;  // Free the dynamically allocated memory

    // ptr now becomes a dangling pointer; it points to a location that has been freed.
    ptr = nullptr;  // It's good practice to set ptr to nullptr after deletion

    return 0;
}
Back to raw_pointers