new and delete Operators in C++

Allocate heap memory in C++ with new and new[], then free it with matching delete and delete[]. Covers uninitialized arrays, leaks, and safer options.

BeginnerMemory Management ProgramsExample 7 of 11
new-and-delete-operators.cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 // Allocate single integer
6 int* ptr = new int(10);
7 cout << "Dynamically allocated integer: " << *ptr << endl;
8
9 // Allocate array
10 int* arr = new int[5];
11 cout << "\nEnter 5 integers: ";
12 for (int i = 0; i < 5; i++) {
13 cin >> arr[i];
14 }
15
16 cout << "Array elements: ";
17 for (int i = 0; i < 5; i++) {
18 cout << arr[i] << " ";
19 }
20 cout << endl;
21
22 // Allocate and initialize array
23 int* arr2 = new int[5]{1, 2, 3, 4, 5};
24 cout << "\nInitialized array: ";
25 for (int i = 0; i < 5; i++) {
26 cout << arr2[i] << " ";
27 }
28 cout << endl;
29
30 // Free memory
31 delete ptr; // Delete single variable
32 delete[] arr; // Delete array (use delete[])
33 delete[] arr2; // Delete array
34
35 cout << "\nMemory freed successfully" << endl;
36
37 // Set pointers to null after deletion
38 ptr = nullptr;
39 arr = nullptr;
40 arr2 = nullptr;
41
42 return 0;
43}

Sample Output

Initialized array: 1 2 3 4 5

From new int[5]{...}.

Memory freed successfully

All delete calls done.

In this one

  • How new and new[] allocate on the heap
  • Why delete must match new and delete[] must match new[]
  • How to initialize a dynamic array with braces
  • What a memory leak is

How it works

  1. 1

    new int(10) allocates one int.

  2. 2

    new int[5] allocates five uninitialized ints, filled by cin.

  3. 3

    new int[5]{1,2,3,4,5} allocates and initializes.

  4. 4

    delete and delete[] free each block.

  5. 5

    Pointers are reset to nullptr.

Edge cases

Mismatched delete

Use delete arr; on an array from new int[5].

Undefined behavior. It may appear to work on some systems and corrupt memory on others.

Double delete

Call delete ptr; twice without resetting.

Undefined behavior, often a crash. Setting ptr = nullptr after the first delete makes the second one a no-op.

What's going on

new asks for memory on the heap at run time and delete gives it back. Heap memory stays alive until you free it, unlike local variables, which vanish at the end of their block.

int* ptr = new int(10); allocates one int, sets it to 10, and returns its address.

int* arr = new int[5]; allocates five ints. They are not initialized; until the loop reads values into them they hold garbage. The sample types 10 20 30 40 50.

int* arr2 = new int[5]{1, 2, 3, 4, 5}; allocates and initializes in one step (C++11 and later).

Freeing must match allocating. delete ptr; for a single object made with new. delete[] arr; and delete[] arr2; for arrays made with new[]. Mixing them, like delete arr on an array, is undefined behavior: it may seem to work, crash, or corrupt memory later.

Forgetting delete entirely is a memory leak: the memory stays reserved until the program exits. In a short program you will not notice; in a long-running server it adds up.

After freeing, the code sets all three pointers to nullptr. That does not make the memory "more freed"; it just stops you from accidentally using the old addresses.

In modern C++, vector<int> replaces new int[] almost everywhere, and unique_ptr replaces bare new for single objects. Both free memory automatically. Learning new/delete first is still worth it, because those tools are built on them.

The only header is <iostream>. It gives you cout for displaying output and cin for taking input from the user.

Understanding new Operator

new Operator Concept:

Allocates memory dynamically at runtime
Returns pointer to allocated memory
Memory allocated on heap (not stack)
Size determined at runtime

Syntax:

pointer = new dataType; // Single variable

pointer = new dataType(value); // With initialization

pointer = new dataType[size]; // Array

Allocating Single Variable

Basic Allocation:

int* ptr = new int(10);

What happens here:

Allocates memory for one integer
Initializes with value 10
Returns pointer to allocated memory
Memory exists until explicitly deleted

Accessing Value:

*ptr // Accesses value 10

Allocating Arrays

Array Allocation:

int* arr = new int[5];

What happens here:

Allocates memory for 5 integers
Returns pointer to first element
Elements can be accessed like array: arr[0], arr[1]
Size can be determined at runtime

Initialized Array:

int* arr2 = new int[5]{1, 2, 3, 4, 5};

What happens here:

Allocates and initializes array
Values provided in braces
Useful for pre-filled arrays

Understanding delete Operator

delete Operator Concept:

Frees memory allocated by new
Returns memory to system
Prevents memory leaks
Must match new with delete

Syntax:

delete pointer; // Single variable

delete[] pointer; // Array

Freeing Single Variable

Deleting Single Variable:

delete ptr;

What happens here:

Frees memory allocated by new
Does not delete pointer variable
Pointer still exists but points to invalid memory
Should set to nullptr after deletion

Freeing Arrays

Deleting Arrays:

delete[] arr; // Use delete[] for arrays

Important Rule:

Use delete[] for arrays allocated with new[]
Using delete instead of delete[] causes undefined behavior
Always match new[] with delete[]

Why delete[]?

Arrays need special cleanup
delete[] calls destructors for all elements
delete only frees first element's memory

Setting Pointers to Null

After Deletion:

delete ptr;

ptr = nullptr; // Good practice

Why?

Prevents dangling pointer
Can check if pointer was deleted
Prevents accidental reuse
Makes code safer

When to Use new/delete

Best For:

Size unknown at compile time
Large objects (avoid stack overflow)
Objects with variable lifetime
Dynamic data structures
Polymorphism with base pointers

Example Scenarios:

User-determined array sizes
Large matrices or data structures
Objects that outlive function scope
Linked lists, trees, graphs

Important Considerations

Memory Leaks:

Always delete what you new
Forgetting delete causes memory leak
Memory not returned to system
Can cause program to run out of memory

Matching Operators:

new must match with delete
new[] must match with delete[]
Mismatch causes undefined behavior

Exception Safety:

If exception occurs, delete may not be called
Use smart pointers (C++11) for automatic cleanup
RAII (Resource Acquisition Is Initialization) pattern

return 0;

This ends the program successfully.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Correct way to free int* a = new int[10];?

Pick an answer to check it.

Question 2

What values does new int[3] hold before you assign them?

Pick an answer to check it.

Questions people ask

Where does new memory come from?

The heap (free store), a region managed at run time.

What happens if I never delete?

A leak. The OS reclaims memory when the program ends, but long-running programs can run out.

What should I use instead?

vector for arrays, unique_ptr or shared_ptr for single objects.