Heap Allocation with new/delete
Manage dynamic memory.
Dynamic Memory with new
The new operator allocates an object on the heap (free store) and returns a pointer to it. Heap objects live until you explicitly free them.
#include <iostream>
int main() {
int* p = new int(42); // heap allocation
std::cout << *p << "\n";
delete p; // release it
}Releasing with delete
Every new must be matched by exactly one delete. Forgetting it leaks memory; doing it twice corrupts the heap.
#include <iostream>
int main() {
double* d = new double(3.5);
std::cout << *d << "\n";
delete d; // exactly once
}All lessons in this course
- Stack Allocation
- Heap Allocation with new/delete
- Object Lifetime
- Common Memory Bugs