new/delete &
Memory Risks
Learn how C++ gives you direct control over memory with new and delete, and discover why that power comes with serious risks.
What is Memory?
Every variable you create in C++ needs a place to live while your program runs. Your computer's RAM (Random Access Memory) is that place: a massive grid of numbered bytes, each with a unique address.
Stack vs Heap
C++ divides memory into two main regions. Understanding their differences is the key to understanding new and delete.
Why Use the Heap?
The new Operator
The new keyword allocates memory on the heap and returns a pointer to it.
The delete Operator
When you're done with heap memory, you must return it to the system using delete. Otherwise, the memory stays reserved forever (within your program's lifetime).
Memory Lifecycle
Heap vs Stack Memory
| Heap (new/delete) | Stack (automatic) | |
|---|---|---|
| Created by | new | Declaration |
| Destroyed by | delete (manual) | Scope exit (auto) |
| Size limit | All available RAM | ~1-8 MB typical |
| Speed | Slower (OS call) | Very fast |
| Risk level | High (leaks, dangling) | Low (automatic) |
How to Use new/delete Safely
Risk 1: Memory Leak
A memory leak occurs when you allocate heap memory but never delete it. The memory stays reserved but becomes unreachable: no pointer points to it anymore.
Risk 2: Dangling Pointer
A dangling pointer is a pointer that still holds the address of memory that has already been freed. Using it causes undefined behavior: crashes, corrupted data, or silent bugs.
Risk 3: Double Delete
Calling delete on the same pointer twice is undefined behavior. The memory manager's internal bookkeeping gets corrupted, often causing a crash.
Example: Single Object
Example: Dynamic Array
Example: Spot the Bug
Common Mistakes
Memory Risks Summary
| Risk | Cause | Prevention |
|---|---|---|
| Memory Leak | Forgot delete | Always pair new with delete |
| Dangling Pointer | Used pointer after delete | Set to nullptr after delete |
| Double Delete | Two pointers to same memory | nullptr check or single owner |
| Wrong Delete | delete vs delete[] mismatch | Match new[] with delete[] |
Question 1 of 5
What does the new operator return?
Question 2 of 5
Which code correctly frees an array allocated with new int[10]?
Question 3 of 5
What happens if you call delete on a pointer, then dereference that same pointer without setting it to nullptr first?
Question 4 of 5
Code:
What memory risk does this code have?
Question 5 of 5
Why is it safe to call delete on a nullptr?