TeachMate
My ProgressJoin Session

Dynamic Memory

0/8 completed · ~0h 24m

All Topics
C++LearnDynamic Memory
1 / 8

Dynamic Memory Allocation

intermediate
3 min read

Dynamic memory allocation creates variables at runtime (on the heap).

Why Dynamic Memory?

  • Size determined at runtime
  • Lifetime extends beyond scope
  • Essential for data structures (linked lists, trees)

new and delete

int* p = new int;       // Allocate one int
*p = 42;               // Assign value
delete p;              // Free memory
p = nullptr;           // Good practice

new[] and delete[]

int* arr = new int[100];  // Allocate array of 100 ints
arr[0] = 42;
delete[] arr;            // Free array
arr = nullptr;

Heap vs Stack

FeatureStackHeap
AllocationAutomaticManual (new/delete)
SpeedFastSlower (system calls)
SizeSmall (1-8 MB)Large (limited by RAM)
LifetimeScope-basedManual

Memory Leaks

void leak() {
    int* p = new int(42);
    return;  // p is lost, memory leaked!
}

Fix:

void safe() {
    int* p = new int(42);
    delete p;  // Free memory
    p = nullptr;
}

When to Use Dynamic Memory

  • Array size unknown at compile time
  • Data that must persist beyond scope
  • Large data that would overflow the stack

Common mistakes: pairing new with delete or new[] with delete (mismatched forms are undefined behavior), and losing the only pointer to a block before deleting it, which leaks it.

Key takeaway: Dynamic allocation (new/delete) manages heap memory — always pair new with delete to avoid leaks.

Try it: Allocate a single int with new, set it to 42, print it, then delete it and set the pointer to nullptr.

TeachMate - Interactive learning platform for bachelor students

HomeLearnJoin Session|2 Subjects