Menu
Coddy logo textTech

Stack vs Heap Memory

Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 12 of 104.

C++ programs use two main memory regions: the stack and the heap. Understanding where your objects live is crucial for writing efficient, bug-free code.

The stack is fast, automatic memory. Variables declared inside functions live here and are automatically destroyed when they go out of scope.

void example() {
    int x = 10;           // Stack allocation
    Player player;        // Stack allocation - destroyed automatically
}   // x and player are destroyed here

The heap is larger but slower memory that you manage manually. Objects on the heap persist until you explicitly delete them.

void example() {
    Player* player = new Player();  // Heap allocation
    // player exists until deleted
    delete player;                   // Manual cleanup required
}

Key differences:

StackHeap
Fast allocationSlower allocation
Limited sizeLarge capacity
Automatic cleanupManual cleanup needed
Fixed-size objectsDynamic-size objects

Use stack allocation for small, short-lived objects. Use heap allocation when objects need to outlive their scope or when their size is determined at runtime.

Forgetting to delete heap memory causes memory leaks, a common source of bugs in C++ programs.

challenge icon

Challenge

Easy

Let's explore the difference between stack and heap memory by building a simple Counter class that tracks how objects are created and destroyed.

You'll create two files to organize your code:

  • Counter.h: Define a Counter class with a private name attribute (string). Include a constructor that takes a name and prints "Creating: <name>", and a destructor that prints "Destroying: <name>". Add a getName() method to return the counter's name.
  • main.cpp: Demonstrate both stack and heap allocation. Read a name from input, then:
    • Create a stack-allocated Counter using that name
    • Create a heap-allocated Counter with the name "HeapCounter"
    • Print both counter names in the format "Stack: <name>" and "Heap: <name>"
    • Delete the heap-allocated counter to prevent a memory leak

Watch how the constructor and destructor messages appear in different orders based on when you create and delete each object. The stack object will be automatically destroyed when main() ends, while the heap object must be explicitly deleted.

Include your header file in main.cpp using #include "Counter.h".

Cheat sheet

C++ programs use two main memory regions: the stack and the heap.

The stack is fast, automatic memory. Variables declared inside functions live here and are automatically destroyed when they go out of scope:

void example() {
    int x = 10;           // Stack allocation
    Player player;        // Stack allocation - destroyed automatically
}   // x and player are destroyed here

The heap is larger but slower memory that you manage manually. Objects on the heap persist until you explicitly delete them:

void example() {
    Player* player = new Player();  // Heap allocation
    // player exists until deleted
    delete player;                   // Manual cleanup required
}

Key differences:

StackHeap
Fast allocationSlower allocation
Limited sizeLarge capacity
Automatic cleanupManual cleanup needed
Fixed-size objectsDynamic-size objects

Use stack allocation for small, short-lived objects. Use heap allocation when objects need to outlive their scope or when their size is determined at runtime. Forgetting to delete heap memory causes memory leaks.

Try it yourself

#include <iostream>
#include <string>
#include "Counter.h"

using namespace std;

int main() {
    // Read name from input
    string inputName;
    cin >> inputName;

    // TODO: Create a stack-allocated Counter using inputName

    // TODO: Create a heap-allocated Counter with name "HeapCounter"

    // TODO: Print stack counter name in format "Stack: <name>"

    // TODO: Print heap counter name in format "Heap: <name>"

    // TODO: Delete the heap-allocated counter to prevent memory leak

    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming