Dynamic Memory
So far, every variable was created on the line that declares it, and removed automatically when its block ended. C++ also lets you ask for memory while the program runs, and give it back yourself when you are done. This is called dynamic memory. It comes from an area of memory called the heap.
Two operators do this work. new asks for memory and gives you a pointer to it. delete gives the memory back.
A common use is an array whose size you only learn while the program runs, for example from the input:
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int* readings = new int[n];
for (int i = 0; i < n; i++) {
cin >> readings[i];
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum += readings[i];
}
cout << "Sum: " << sum << "\n";
delete[] readings;
return 0;
}
Output:
Sum: 20
With the input 3 and then 7 9 4, new int[n] reserves space for 3 ints on the heap. It returns a pointer to the first one. As you saw in the last lesson, you can use [ ] on that pointer, so readings works like a normal array.
delete[] readings; gives the memory back. Use delete[] (with brackets) for memory you got with new ...[n].
For a single value, use new without brackets, and delete without brackets:
int* count = new int(5);
cout << *count << "\n";
delete count;
Output:
5
You must give it back
C++ does not free heap memory for you. If you forget delete, the memory stays reserved until the program ends. A program that runs for days and keeps forgetting will use more and more memory. This bug is called a memory leak.
The opposite mistakes are bugs too: calling delete twice on the same pointer, or using the memory after delete. C++ does not check for any of these.
That is why most modern C++ code does not use new and delete directly. A vector also stores its elements on the heap, and its size can be decided while the program runs. The difference is that a vector gives its memory back by itself. So when you need a list of values, use a vector. Smart pointers call delete for you. The Smart Pointers lesson, at the end of the Object-Oriented Programming section, shows them.
You will still find new and delete in a lot of existing code, so it is good to know them.
In the exercise, create an array with new, fill it with square numbers, and free it with delete[].