← Back to C++ Course | Chapter 14: Memory Management | Lesson 1 of 6

C++ Memory Management

Memory management in C++ is the process of manually allocating memory on the heap with new and releasing it with delete, or using RAII-based smart pointers to automate that lifecycle safely.

What is Memory Management?

Memory management in C++ is the process of allocating space for data as a program needs it and releasing that space when it's no longer needed, done manually with new/delete or automatically through RAII-based smart pointers.

Example: What is Memory Management?

cpp
#include <iostream>

int main() {
	int *ptr = new int(5);
	std::cout << *ptr << std::endl;
	delete ptr;
	return 0;
}

Stack vs Heap Memory

C++ programs use two main regions of memory: the stack, which automatically manages local variables tied to function calls, and the heap, a pool of memory that must be explicitly allocated and freed (or managed by a smart pointer).

Example: Stack vs Heap Memory

cpp
#include <iostream>

int main() {
	int stackVar = 10;
	int *heapVar = new int(20);
	std::cout << stackVar << " " << *heapVar << std::endl;
	delete heapVar;
	return 0;
}

Static vs Dynamic Allocation

Static allocation, like a regular array declaration, fixes memory size at compile time, while dynamic allocation, using new, lets a program decide how much memory it needs while it's actually running.

Example: Static vs Dynamic Allocation

cpp
#include <iostream>

int main() {
	int staticArr[3] = {1, 2, 3};
	int size = 3;
	int *dynamicArr = new int[size];
	dynamicArr[0] = 5;
	std::cout << staticArr[0] << " " << dynamicArr[0] << std::endl;
	delete[] dynamicArr;
	return 0;
}

The Allocate-Use-Free Lifecycle

Every block of dynamically allocated memory follows a lifecycle: it's allocated with new, used through a pointer, and then released exactly once with delete (or delete[] for arrays) when it's no longer needed.

Example: The Allocate-Use-Free Lifecycle

cpp
#include <iostream>

int main() {
	int *ptr = new int(5);
	std::cout << *ptr << std::endl;
	delete ptr;
	return 0;
}

Modern C++ Prefers Smart Pointers

Modern C++ encourages using smart pointers like unique_ptr and shared_ptr instead of raw new/delete, since they automatically release their memory when they go out of scope, preventing leaks and use-after-free bugs.

Example: Modern C++ Prefers Smart Pointers

cpp
#include <iostream>
#include <memory>

int main() {
	std::unique_ptr<int> ptr = std::make_unique<int>(42);
	std::cout << *ptr << std::endl;
	return 0;
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.