C++ Memory: new and delete
Local variables are created when a function starts and destroyed when it returns; they live on the stack. Sometimes an object must outlive the function that creates it, or its size is only known while the program runs. Such objects are created on the heap with new, and must be destroyed with delete.
new and delete for one object
ExampleTry it in the editor
#include <iostream>
int main() {
int* p = new int(42); // an int on the heap
std::cout << *p << "\n";
*p += 8;
std::cout << *p << "\n";
delete p; // give the memory back
p = nullptr; // p no longer points anywhere
return 0;
}Output
42 50
new[] and delete[] for arrays
An array created with new[] must be freed with delete[], not plain delete:
ExampleTry it in the editor
#include <iostream>
int main() {
int n = 5;
int* squares = new int[n];
for (int i = 0; i < n; i++) squares[i] = (i + 1) * (i + 1);
for (int i = 0; i < n; i++) std::cout << squares[i] << " ";
std::cout << "\n";
delete[] squares;
return 0;
}Output
1 4 9 16 25
The rules
- Every
newneeds exactly onedelete, and everynew[]exactly onedelete[]. - Forgetting
deleteis a memory leak: the memory stays reserved until the program ends. With Safe mode on, the editor reports leaks when the program finishes. - Using memory after
delete(a dangling pointer) or deleting twice is a serious bug. Setting the pointer tonullptrafterdeletemakes such mistakes easier to catch. - If
newcannot find memory, it throws astd::bad_allocexception.
Why modern C++ rarely writes delete
Getting every delete right is hard, especially when a function can return early or an exception is thrown. Modern C++ uses classes that manage memory for you:
std::vectorinstead ofnew[]for arrays whose size is known at run time;std::stringinstead of character arrays;std::unique_ptrandstd::shared_ptr(see Smart Pointers) for single objects.
ExampleTry it in the editor
#include <iostream>
#include <vector>
int main() {
int n = 5;
std::vector<int> squares(n); // the vector owns its memory
for (int i = 0; i < n; i++) squares[i] = (i + 1) * (i + 1);
for (int s : squares) std::cout << s << " ";
std::cout << "\n";
return 0; // freed automatically
}Output
1 4 9 16 25
Learn new and delete to understand what happens underneath, then let the standard library do the work.
Practice exercises
- Ask the user for a size, create an array of that many
doublevalues withnew[], fill it, print the average anddelete[]it. - With Safe mode on, remove the
delete[]and read the leak report. - Rewrite exercise 1 with a
std::vectorand compare the two versions.