Lesson 2 of 7
new/delete & Memory Bugs
Raw `new`/`delete` is the low-level mechanism for heap allocation in C++. In modern C++, **you should almost never use them directly** - use smart pointers instead. But understanding what they do under the hood is essential. The three critical heap bugs are: **memory leak** (allocated but never freed), **use-after-free** (accessing freed memory), and **double-free** (freeing the same pointer twice).
new/delete - The Three Heap Bugs & How to Detect Them
#include <iostream>
#include <new>
// ── Raw new/delete - understand before modernising ───────────
void raw_allocation_demo() {
// Single objects
int* p1 = new int(42);
double* p2 = new double(3.14);
std::cout << *p1 << " " << *p2 << "
";
delete p1; // free single object
delete p2;
// Arrays
int* arr = new int[5]{1, 2, 3, 4, 5}; // initialised
for (int i = 0; i < 5; ++i) std::cout << arr[i] << " ";
std::cout << "
";
delete[] arr; // MUST be delete[], not delete!
// Placement new - construct in existing memory (advanced)
alignas(int) char buf[sizeof(int)];
int* placed = new(buf) int(99); // constructs in char buffer
std::cout << *placed << "
";
placed->~int(); // explicit destructor call (paired with placement new)
}
// ── Memory Bug 1: Memory Leak ─────────────────────────────────
void memory_leak() {
int* p = new int(5);
// ... if this function returns without delete p:
// p is LEAKED - bytes allocated but never returned to OS
// Valgrind: "definitely lost: 4 bytes"
// ASAN: "==ERROR== detected memory leaks" at exit
// The fix: use RAII / smart pointers (next topics)
delete p; // correct: explicit cleanup (or use unique_ptr)
}
// ── Memory Bug 2: Use-After-Free ──────────────────────────────
void use_after_free() {
int* p = new int(42);
delete p;
// std::cout << *p; ← UNDEFINED BEHAVIOUR!
// May print garbage, may crash, may print 42 (freed memory reused)
// ASAN: "heap-use-after-free: READ of size 4"
p = nullptr; // defensive: nullptr after delete
// Now *p would immediately crash (null dereference) - safer failure
}
// ── Memory Bug 3: Double-Free ─────────────────────────────────
void double_free() {
int* p = new int(7);
int* q = p; // two pointers to same object
delete p;
// delete q; ← UNDEFINED BEHAVIOUR! Same memory freed twice
// Typically crashes heap allocator, corrupts heap metadata
// ASAN: "double-free or corruption"
p = nullptr; // only nulls p, not q!
}
// ── Detecting bugs: compile and run with ASAN ─────────────────
// g++ -Wall -g -fsanitize=address,undefined bug.cpp -o bug
// ./bug <- ASAN reports errors with stack traces
// Also: valgrind --leak-check=full ./bug
int main() {
raw_allocation_demo();
return 0;
}Common Mistakes
- `delete` doesn't null the pointer - after `delete p`, `p` still holds the old address. Reading or writing through it is use-after-free. Set `p = nullptr` after every `delete` so any subsequent dereference safely crashes with null-dereference rather than corrupting heap.
- Mixing `malloc`/`free` with `new`/`delete` - `malloc` returns raw memory without calling constructors; `free` doesn't call destructors. `new` and `delete` do. Never mix them on the same pointer.
- Forgetting `delete[]` for arrays - `new T[n]` calls constructors for each of the n elements. `delete` (non-array) only destructs and frees the first element. `delete[]` destructs all n elements. The mismatch is UB and causes subtle bugs.
Tip
Tip
Practice newdelete Memory Bugs in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Why Raw Pointer Manual Management is Dangerous: Leaks, Dangling References, and Double Free
Practice Task
Note
Practice Task - (1) Write a working example of newdelete Memory Bugs from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with newdelete Memory Bugs is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.
Key Takeaways
- Raw `new`/`delete` is the low-level mechanism for heap allocation in C++.
- `delete` doesn't null the pointer - after `delete p`, `p` still holds the old address. Reading or writing through it is use-after-free. Set `p = nullptr` after every `delete` so any subsequent dereference safely crashes with null-dereference rather than corrupting heap.
- Mixing `malloc`/`free` with `new`/`delete` - `malloc` returns raw memory without calling constructors; `free` doesn't call destructors. `new` and `delete` do. Never mix them on the same pointer.
- Forgetting `delete[]` for arrays - `new T[n]` calls constructors for each of the n elements. `delete` (non-array) only destructs and frees the first element. `delete[]` destructs all n elements. The mismatch is UB and causes subtle bugs.
Finished this lesson?