Skip to content

Chapter 11 of 31

Dynamic Memory Management

Understand new, delete, arrays, ownership hazards, RAII, and safer containers.

36 minutes 10 quick checksBy Subha Prasad
Lesson 11 of 31Course navigation

Lesson content

Read, practise, then check your understanding

Automatic objects are destroyed when their scope ends. Dynamic storage lasts until its owner releases it, which is useful when size or lifetime is not known locally. A new expression allocates and constructs; delete destroys and deallocates. Arrays require matching new[] and delete[].

int* number = new int{42};
delete number;
number = nullptr;

int* values = new int[3]{1, 2, 3};
delete[] values;

Mismatched deletion, double deletion, leaks, and use-after-free are serious defects. Allocation can throw std::bad_alloc. Manual code becomes especially fragile across early returns and exceptions.

Prefer RAII ownership

#include <memory>
#include <vector>

auto item = std::make_unique<int>(42);
std::vector<int> values{1, 2, 3};

RAII binds a resource to an object whose destructor releases it. std::vector owns variable-size arrays; std::string owns text; std::unique_ptr owns one dynamic object. These types make cleanup deterministic and exception-safe.

Use std::make_unique rather than a visible owning new. Use std::shared_ptr only when ownership is truly shared, not simply to avoid deciding who owns an object. Raw pointers and references remain useful as non-owning views. The Rule of Zero says a class composed of RAII members should usually declare no custom destructor, copy operation, or move operation.

Knowledge check

Answer every question correctly to complete this chapter.

Which expression allocates one int?
Which form releases memory from new int?
Which release matches new T[count]?
What should modern C++ prefer over owning raw new?
What does new normally do on allocation failure?
What is a memory leak?
What is use-after-delete?
Is delete nullptr valid?
Why should a base destructor be virtual for polymorphic deletion?
What should own a dynamic sequence in most code?

0 of 10 checks passed

Your progress is saved on this device.