new and delete (C++)

new allocates memory on the heap at runtime and returns a pointer to it, while delete frees that memory. Every new must be matched by exactly one delete, or you get a memory leak.

C++

Heap allocation lets you create objects whose size or lifetime isn't known at compile time. For arrays, use new[] and the matching delete[].

Manual memory management is error-prone — forgetting delete leaks memory, and deleting twice or using freed memory causes crashes. Modern C++ recommends smart pointers and containers instead of raw new/delete.

Syntax

T* p = new T(args); /* ... */ delete p;

Examples

C++

#include <iostream>

int main() {
    int* p = new int(42);
    std::cout << *p << std::endl;
    delete p;
    return 0;
}

Output:

42

Learn it in a lesson

See also

Back to the Dictionary