Legacy C++ › 2. Pointers, References and Memory
Dynamic Memory: new and delete
Heap allocation, new[]/delete[], leaks and placement new.
Explanation
Objects created with new live on the heap until you destroy them with delete. new allocates memory and runs the constructor; delete runs the destructor and frees the memory. Arrays use the matching pair new[] / delete[].
If allocation fails, new throws std::bad_alloc. new (std::nothrow) returns a null pointer instead. Deleting a null pointer is safe and does nothing.
Placement new constructs an object in memory you already own: new (buffer) T(args); you must call the destructor manually.
Example
#include <iostream>
#include <new>
struct Point {
int x, y;
Point(int x_, int y_) : x(x_), y(y_) { std::cout << "ctor\n"; }
~Point() { std::cout << "dtor\n"; }
};
int main() {
Point* p = new Point(1, 2); // allocate + construct
std::cout << p->x << "," << p->y << "\n";
delete p; // destruct + free
p = 0; // avoid a dangling pointer
int* arr = new int[4](); // () zero-initializes
arr[0] = 10;
delete[] arr; // must match new[]
try {
char* huge = new char[static_cast<std::size_t>(-1)]; // fails
delete[] huge;
} catch (const std::bad_alloc&) {
std::cout << "out of memory\n";
}
// placement new: construct in memory you obtained separately
void* raw = ::operator new(sizeof(Point)); // raw, correctly aligned memory
Point* q = new (raw) Point(3, 4); // construct only
q->~Point(); // destroy only, by hand
::operator delete(raw); // free only
return 0;
}
Common pitfalls
- Memory leak: every path out of the function (including exceptions) must reach the
delete. - Mismatched forms:
deleteon anew[]pointer, ordelete[]on anewpointer, is undefined behavior. - Double delete and use after delete: set pointers to
0after deleting, and prefer ownership types. malloc/freedo not call constructors/destructors. Never mix them withnew/delete.- Forgetting that a raw
newexpression followed by a throwing call can leak (see Exception Safety).
Legacy vs modern
Raw new/delete in application code is a code smell. Use containers (std::vector), RAII wrappers, and in C++11+ std::unique_ptr / std::make_unique.
Exercises
1. What is wrong with int* p = new int[10]; delete p;?
It must be delete[] p;. Using plain delete on an array is undefined behavior.