Dynamic Memory: new and delete in C++
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.
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.
Arrays need delete[]
new int[n] pairs with delete[] a; — plain delete on array-new is undefined behavior, a classic legacy bug.
Leaks and double-frees
Losing the last pointer without deleting leaks; deleting twice corrupts the heap. Both are silent until they explode.
Prefer owners
std::vector replaces new[] arrays, unique_ptr replaces owning raw pointers — manual delete survives mainly in old code.
#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;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.