Learn C++
#include "arrayspointers/dynamic_memory.hpp"

Dynamic Memory: new and delete in C++

//concept

Stack memory is automatic but fixed at compile time; new allocates from the heap at run time with sizes known only while running. int* p = new int(5); and int* a = new int[n]; create single objects and arrays whose lifetime you control — and must end with matching delete / delete[] or the memory leaks.

Manual new/delete is error-prone (leaks, double-frees, mismatched forms), so modern C++ treats it as a low-level tool: containers own dynamic storage, smart pointers own single objects, and raw new appears mostly in teaching and legacy code. Still, every C++ programmer must understand it to debug leaks and read older systems.

//how it works
1

new allocates, delete frees

int* p = new int(5); reserves one heap int holding 5; delete p; returns it. Every new needs exactly one delete.

2

Arrays need delete[]

new int[n] pairs with delete[] a; — plain delete on array-new is undefined behavior, a classic legacy bug.

3

Leaks and double-frees

Losing the last pointer without deleting leaks; deleting twice corrupts the heap. Both are silent until they explode.

4

Prefer owners

std::vector replaces new[] arrays, unique_ptr replaces owning raw pointers — manual delete survives mainly in old code.

//example
#include <iostream>
 
int main() {
int n = 3;
int* a = new int[n]{1, 2, 3};
int sum = 0;
for (int i = 0; i < n; ++i) sum += a[i];
std::cout << sum << std::endl;
delete[] a;
return 0;
}
Output
6
1new int[n]{1,2,3} allocates three heap ints (n known only at run time) and initializes them.
2Ordinary indexing sums the heap array exactly like a stack one — 1+2+3 = 6.
3delete[] a; frees all three with the array form; forgetting it would leak until program exit.
//use cases
Runtime-sized buffers when the length comes from input or files
Understanding leak reports from sanitizers and Valgrind in legacy code
Recognizing mismatched new/delete[] as undefined behavior in reviews
Migrating manual arrays to vector and owning pointers to unique_ptr

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.