# Stack, Heap and Object Lifetime — C++

Source: https://www.skillbyai.com/en/cpp/m-stack-heap

> Explain automatic and dynamic storage and the dangers of manual new and delete.

## Where objects live and when they die

Every C++ object has a **storage duration** and a **lifetime**. **Automatic** objects (local variables) live on the **stack**: created when execution reaches their definition and destroyed automatically, in reverse order, when the enclosing scope ends. Allocation is extremely fast and cleanup is guaranteed. **Dynamic** objects live on the **heap** (the free store), created with `new` and destroyed only when someone calls `delete`. That flexibility brings classic bugs: **memory leaks** (forgetting `delete`), **double deletes** (calling `delete` twice), **dangling pointers** (using memory after it was deleted) and mismatched `new[]` with `delete`. **Static** objects (globals, `static` locals) live for the whole program. In modern C++ you almost never write `new` and `delete` directly: containers such as `std::vector` and `std::string` manage their own heap memory, and **smart pointers** own dynamically allocated objects, so cleanup is automatic even when exceptions are thrown.

## Stack frames and the heap

Local variables live in stack frames that disappear on return; heap objects stay until released.

![A vertical stack of frames on the left, each with small boxes, and arrows from some boxes to blocks scattered in a larger area on the right.](assets/figures/cpp/section-3-map.svg) — Figure 3.1 — Automatic storage on the stack and dynamic storage on the heap.

## Manual memory versus automatic management

The raw version leaks if anything throws between new and delete.

```cpp
#include <memory>
#include <string>
#include <vector>

void risky() {
    auto* names = new std::vector<std::string>{"Asha", "Ravi"};   // heap allocation
    process(*names);           // if this throws, delete below never runs -> leak
    delete names;
}

void safe() {
    std::vector<std::string> names{"Asha", "Ravi"};   // the vector manages its own heap memory
    process(names);            // freed automatically when names goes out of scope
}

void when_you_need_heap_object() {
    auto report = std::make_unique<std::string>("quarterly report");
    process_text(*report);     // freed automatically, even if an exception is thrown
}
```

## No naked new

The C++ Core Guidelines recommend avoiding explicit `new` and `delete` in application code. If you see `new`, ask which container or smart pointer should own that object instead.

**Quiz:** What happens to a local std::vector when the function it was declared in returns?

- [x] Its destructor runs automatically and frees its memory
- [ ] It leaks unless you call delete
- [ ] It moves to the heap
- [ ] It stays alive until the program ends

*Answer:* Its destructor runs automatically and frees its memory. Automatic objects are destroyed at the end of their scope, and the vector frees its buffer.
