Lesson 15 of 45
C++Lesson 15: Dynamic Memory Allocation (new, delete)
10 min
Course progress33%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 15 of 45
C++10 min
Keep these ideas in mind as you work through the lesson.
new, delete)C++ lets you allocate objects on the heap with new and release them with delete. This gives you control over lifetime beyond the current scope.
// Single object
int* p = new int(5); // value‑initialises to 5
std::cout << \"*p = \" << *p << '\
';
delete p; // free memory
// Dynamic array
int* arr = new int[3]{1, 2, 3};
for (int i = 0; i < 3; ++i) {
std::cout << arr[i] << ' ';
}
std::cout << '\
';
delete[] arr; // note the []
Failure to delete leads to memory leaks. Modern C++ encourages RAII (Resource Acquisition Is Initialization) to automate cleanup.
Tip: Prefer smart pointers (
std::unique_ptr<T[]>) for dynamic arrays to avoid manualdelete[].
<Alert type="info">Never call delete on memory allocated with malloc, and never call free on memory allocated with new.