Dynamic Allocation (new & delete Hazards)

🟡 Intermediate

📖 Definition

Raw dynamic allocation uses new to allocate heap storage and delete (or delete[] for arrays) to free it. Forgetting to deallocate results in memory leaks, while accessing deallocated memory causes dangling pointer UB.

💡 Code Example

#include <iostream>

int main() {
    int* p = new int(42); // Heap allocation
    std::cout << "Heap val: " << *p << "\n";

    delete p; // Explicit deallocation
    p = nullptr; // Prevent dangling pointer usage
    return 0;
}