Module 4

Dynamic Memory Allocation & Pointers

20 mins read

Lesson 1: Heap Allocation & Smart Pointers

1.1 `new` and `delete` Operators

Managing heap memory allocation using raw pointers or modern `std::unique_ptr` smart pointers to prevent memory leaks.

C++
#include <iostream>
#include <memory>

int main() {
    // Modern C++ Smart Pointer
    std::unique_ptr<int> ptr = std::make_unique<int>(42);
    std::cout << "Value: " << *ptr << std::endl;
    return 0; // Memory automatically released!
}