0
0
C++programming~5 mins

delete operator in C++

Choose your learning style9 modes available
Introduction

The delete operator frees memory that was previously allocated with new. It helps keep your program from using too much memory.

When you create an object using <code>new</code> and want to remove it after use.
When you want to avoid memory leaks by cleaning up unused memory.
When you allocate an array with <code>new[]</code> and want to free it.
When managing resources manually in simple programs without smart pointers.
Syntax
C++
delete pointer;
delete[] pointer_to_array;

Use delete for single objects allocated with new.

Use delete[] for arrays allocated with new[].

Examples
Deletes a single integer allocated on the heap.
C++
int* p = new int;
// use p
delete p;
Deletes an array of 5 integers allocated on the heap.
C++
int* arr = new int[5];
// use arr
delete[] arr;
Sample Program

This program creates a single integer and an array on the heap, prints their values, and then frees the memory using delete and delete[].

C++
#include <iostream>

int main() {
    int* number = new int(42);
    std::cout << "Number: " << *number << std::endl;
    delete number;  // free memory

    int* array = new int[3]{1, 2, 3};
    std::cout << "Array elements: ";
    for (int i = 0; i < 3; ++i) {
        std::cout << array[i] << " ";
    }
    std::cout << std::endl;
    delete[] array;  // free array memory

    return 0;
}
OutputSuccess
Important Notes

Always match new with delete and new[] with delete[] to avoid undefined behavior.

After deleting, set pointers to nullptr to avoid dangling pointers.

Using delete on memory not allocated with new causes errors.

Summary

The delete operator frees memory allocated with new.

Use delete for single objects and delete[] for arrays.

Proper use prevents memory leaks and keeps programs efficient.