void f() {
int a = 10; // stack
int* p = new int(20); // heap
delete p; // must free heap memory
}
C++
Topics in this category
Casting & Conversions
Compilation & Linking
Concepts & Constraints
Concurrency
Const Correctness
Constexpr & Compile-Time
Coroutines
Enums & Enum Classes
Exception Handling
I/O Streams
Lambda Expressions
Memory Management
Modern C++
Move Semantics
Namespaces
OOP & Classes
Operator Overloading
Preprocessor & Macros
RAII & Smart Pointers
Ranges & Views
C++
Memory Management
The stack is a region of memory for automatic (local) variables, managed by the compiler with LIFO allocation and fast, deterministic lifetime tied to scope. The heap (free store) is for dynamic allocation via new/malloc, managed manually (or by smart pointers), with flexible lifetime but slower allocation and risk of leaks.
Real-world example
Local loop counters live on the stack; a dynamically sized buffer is allocated on the heap.
RAII & Smart Pointers
References & Pointers
Memory Management
new allocates memory on the heap and constructs an object, returning a pointer; delete calls the destructor and frees the memory. For arrays use new[] and delete[]. Every new must be matched by exactly one delete (and new[] with delete[]) or you get leaks or undefined behavior.
int* p = new int(5); delete p;
int* a = new int[10]; delete[] a;
Real-world example
A container implementation uses new[]/delete[] to manage its underlying buffer.
RAII & Smart Pointers
Memory Management
Memory Management
A memory leak occurs when heap memory is allocated but never freed, so it remains reserved for the program's lifetime, gradually exhausting available memory. Leaks happen when a delete is missed, a pointer is overwritten before freeing, or an exception skips the cleanup. RAII/smart pointers prevent most leaks.
int* p = new int(1);
p = new int(2); // first allocation leaked
Real-world example
A long-running server slowly consumes all memory because a handler forgets to free per-request buffers.
RAII & Smart Pointers
Memory Management
Memory Management
A dangling pointer points to memory that has been freed or gone out of scope, so dereferencing it is undefined behavior. It arises from using a pointer after delete, returning the address of a local variable, or holding a pointer/iterator into a container after it reallocates. Setting freed pointers to nullptr and using smart pointers reduces the risk.
int* p = new int(5);
delete p;
*p = 10; // dangling: undefined behavior
Real-world example
A cached raw pointer crashes the app after the object it referenced was destroyed.
References & Pointers
RAII & Smart Pointers
Memory Management
malloc/free are C library functions that only allocate/free raw memory and don't call constructors or destructors; new/delete are C++ operators that also construct and destruct objects and are type-safe (no cast needed). In C++ you should use new/delete (or better, smart pointers), not malloc, for objects with non-trivial lifetimes.
MyClass* a = (MyClass*)malloc(sizeof(MyClass)); // no ctor called
MyClass* b = new MyClass(); // ctor called
Real-world example
Mixing malloc with a C++ class skips its constructor, leaving members uninitialized and crashing later.
RAII & Smart Pointers
Memory Management
Memory Management
Placement new constructs an object at a pre-allocated memory address rather than allocating new memory. It's used to separate allocation from construction (e.g., in custom allocators, memory pools, or containers). You must manually call the destructor for placement-new objects; you don't delete them.
alignas(MyClass) char buf[sizeof(MyClass)];
MyClass* p = new (buf) MyClass(); // construct in buf
p->~MyClass(); // explicit destruction
Real-world example
A memory pool uses placement new to construct objects in a pre-allocated block, avoiding per-object heap calls.
RAII & Smart Pointers
STL
Memory Management
A shallow copy copies pointer values, so two objects share the same heap memory—leading to double-free or dangling issues when one is destroyed. A deep copy allocates new memory and copies the pointed-to data, giving each object independent ownership. The Rule of Three/Five ensures correct copy/move semantics for classes managing resources.
// Deep copy in copy constructor
MyClass(const MyClass& o) : data(new int[o.n]), n(o.n) {
std::copy(o.data, o.data + n, data);
}
Real-world example
A class that shallow-copies a buffer double-frees it, crashing when both copies are destroyed.
Move Semantics
OOP & Classes
Memory Management
Alignment is the requirement that objects be placed at memory addresses that are multiples of their alignment (often their size), so the CPU can access them efficiently (or at all, on some architectures). alignof queries it and alignas sets it. Misalignment can cause performance penalties or hardware faults; it also affects struct padding and layout.
struct S { char c; int i; }; // padding inserted for i's alignment
static_assert(alignof(int) == 4);
Real-world example
A struct is reordered and padded so each member meets its alignment, changing sizeof.
OOP & Classes
Memory Management
Memory Management
A memory leak is failing to free heap memory. A resource leak is more general—failing to release any acquired resource: file handles, sockets, mutex locks, database connections, or OS handles. RAII addresses both by tying resource release to object destruction, so any acquired resource is freed automatically when its owner goes out of scope.
{
std::ofstream f("log.txt"); // RAII: file closed at scope end
} // f's destructor releases the file handle
Real-world example
Forgetting to close file handles exhausts the OS descriptor limit; RAII wrappers prevent it.
RAII & Smart Pointers
Exception Handling
Memory Management
A stack overflow happens when the call stack exceeds its size limit—commonly from very deep or infinite recursion, or allocating very large local arrays/objects on the stack. It typically crashes the program. Fixes include converting recursion to iteration, reducing recursion depth, or allocating large data on the heap.
void recurse() { recurse(); } // infinite recursion -> stack overflow
Real-world example
A recursive tree traversal on a deeply unbalanced tree overflows the stack and crashes.
Memory Management
References & Pointers
Memory Management