Lesson 125 +10 XP

new and delete

new and delete

C++ lets you ask for heap memory with the new operator and give it back with delete. This is the classic, manual way to manage dynamic memory.

Allocating a single value

new creates an object on the heap and hands you a pointer to it:

int* p = new int(5);   // heap int starts at 5
cout << *p;            // 5

The value 5 lives on the heap. The pointer p holds its address, and *p reads the value through the pointer.

Releasing memory with delete

Whatever you allocate with new, you release with delete:

int* p = new int(5);
delete p;   // give the heap memory back

After delete p, the memory is free, and using p again is undefined behavior.

Allocating arrays

For a block of many values, use new[] and release it with delete[]:

int* arr = new int[10];
delete[] arr;

The brackets must match: new[] is matched with delete[], and bare new with bare delete.

The memory-leak trap

If you call new but never call delete, the memory is kept until the program exits - it leaks. Forgetting, or overwriting the pointer before deleting, both cause leaks.

The modern advice

In everyday code, avoid raw new and delete. Prefer std::vector, std::make_unique, std::make_shared, or any object whose lifetime manages itself. Manual memory management is only for low-level or performance-critical work.

TL;DR

  • int* p = new int(5); creates one heap int.
  • delete p; frees that single allocation.
  • new int[10] must be matched with delete[] arr.
  • Forgotten delete means a memory leak.
  • Use std::vector and smart pointers instead of raw new/delete.