Skip to content
  • Stack, Heap & Object Lifetime · C++

Stack, Heap & Object Lifetime

LearnViaNotes @learnvianotes· 3 min read

Where an object lives decides how long it lives. C++ has four storage durations; knowing them is the key to avoiding dangling pointers.

Memory segments of a process

RegionHoldsLifetimeManaged by
StackLocal variables, parameters, return addressesUntil the enclosing block endsAutomatic (push/pop)
Heap (free store)Objects from new / containers' buffersUntil deleteYou (or RAII owners)
Static / global dataGlobals, static locals & membersWhole programRuntime
Code (text)Machine instructions, string literals (read-only data)Whole programLoader

Storage durations

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

struct Tracer {
    std::string name;
    explicit Tracer(std::string n) : name(std::move(n)) { std::cout << "+ " << name << '\n'; }
    ~Tracer() { std::cout << "- " << name << '\n'; }
};

Tracer global("static");                 // static: before main, destroyed after main

void f() {
    static Tracer once("static-local");  // created on first call only
    Tracer local("automatic");           // destroyed at the end of f
}

int main() {
    std::cout << "main starts\n";
    f();
    f();
    auto heap = std::make_unique<Tracer>("dynamic");   // lives until its owner lets go
    heap.reset();
    std::cout << "main ends\n";
}
Output
+ static
main starts
+ static-local
+ automatic
- automatic
+ automatic
- automatic
+ dynamic
- dynamic
main ends
- static-local
- static
  • Automatic — block-scoped locals. Destroyed in reverse order of construction when the block ends.

  • Static — globals, namespace variables, static locals/members. Static locals are initialised on first use (thread-safe since C++11).

  • Dynamic — new/delete, or owned by smart pointers/containers.

  • Thread — thread_local variables: one instance per thread.

Stack vs heap

StackHeap
Allocation speedVery fast (move a pointer)Slower (allocator bookkeeping)
Size limitSmall (~1–8 MB)Large (up to available memory)
LifetimeTied to scopeExplicit / owner-controlled
FragmentationNonePossible
Typical failureStack overflow (deep recursion, huge local arrays)Leaks, use-after-free

Object size & alignment

C++
#include <iostream>
struct Padded  { char a; int b; char c; };    // 1 + 3 pad + 4 + 1 + 3 pad
struct Ordered { int b; char a; char c; };    // 4 + 1 + 1 + 2 pad
struct Empty {};
int main() {
    std::cout << sizeof(Padded) << ' ' << sizeof(Ordered) << ' ' << alignof(int) << ' ' << sizeof(Empty) << '\n';
}
Output
12 8 4 1

Why is the stack faster than the heap?

In what order are local objects destroyed?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report