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 hereThe 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:
| Stack | Heap |
|---|---|
| Fast allocation | Slower allocation |
| Limited size | Large capacity |
| Automatic cleanup | Manual cleanup needed |
| Fixed-size objects | Dynamic-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
EasyLet'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 aCounterclass with a privatenameattribute (string). Include a constructor that takes a name and prints"Creating: <name>", and a destructor that prints"Destroying: <name>". Add agetName()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
Counterusing that name - Create a heap-allocated
Counterwith 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
- Create a stack-allocated
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 hereThe 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:
| Stack | Heap |
|---|---|
| Fast allocation | Slower allocation |
| Limited size | Large capacity |
| Automatic cleanup | Manual cleanup needed |
| Fixed-size objects | Dynamic-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;
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesC++ Build & CompilationHeader Files & Source FilesNamespaces & ScopeIntroduction to OOP in C++Classes vs ObjectsThe 'this' PointerMethods (Member Functions)Attributes (Data Members)Ctors & Dtors BasicsRecap - Simple Calculator4Class Properties
Instance vs Static MembersGetters and SettersConst Member FunctionsMutable KeywordStatic Methods and VariablesFriend Functions & ClassesRecap - Bank Account Manager7Inheritance
Basic InheritanceInheritance Access LevelsCtor & Dtor Call OrderMethod OverridingVirtual Functions & VTableMultiple InheritanceVirtual InheritanceRecap - Employee Hierarchy2Memory Management
Stack vs Heap MemoryPointers and ReferencesDynamic Memory (new/delete)Smart Pointers in C++RAII in C++Recap - Dynamic Array Manager5Encapsulation
Access Specifiers in C++Access Specifiers In DepthInformation HidingStruct vs ClassNested & Inner ClassesRecap - Student Records System8Polymorphism
Compile vs Runtime PolymorphFunction OverloadingVirtual Functions RevisitedPure Virtual FunctionsAbstract ClassesInterface Design in C++Dynamic Casting & RTTIRecap - Shape Calculator3Constructors & Destructors
Default ConstructorParameterized ConstructorCopy ConstructorMove ConstructorConstructor Init ListsDelegating ConstructorsDestructor Deep DiveRule of Three / Five / ZeroRecap - String Class6Operator Overloading
Intro to Operator OverloadArithmetic Operator OverloadComparison Operator OverloadStream OperatorsAssignment Operator Overload[] and () Operator OverloadType Conversion OperatorsRecap - Matrix Class9Templates
Function TemplatesClass TemplatesTemplate SpecializationVariadic TemplatesSFINAE & Type Traits BasicsRecap - Generic Container