new and delete Operators

Dynamic Memory Allocation using new and delete in C++

C++Beginner
C++
#include <iostream>
using namespace std;

int main() {
    // Allocate single integer
    int* ptr = new int(10);
    cout << "Dynamically allocated integer: " << *ptr << endl;
    
    // Allocate array
    int* arr = new int[5];
    cout << "\nEnter 5 integers: ";
    for (int i = 0; i < 5; i++) {
        cin >> arr[i];
    }
    
    cout << "Array elements: ";
    for (int i = 0; i < 5; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    
    // Allocate and initialize array
    int* arr2 = new int[5]{1, 2, 3, 4, 5};
    cout << "\nInitialized array: ";
    for (int i = 0; i < 5; i++) {
        cout << arr2[i] << " ";
    }
    cout << endl;
    
    // Free memory
    delete ptr;        // Delete single variable
    delete[] arr;      // Delete array (use delete[])
    delete[] arr2;     // Delete array
    
    cout << "\nMemory freed successfully" << endl;
    
    // Set pointers to null after deletion
    ptr = nullptr;
    arr = nullptr;
    arr2 = nullptr;
    
    return 0;
}

Output

Dynamically allocated integer: 10
Enter 5 integers: 10 20 30 40 50
Array elements: 10 20 30 40 50

Initialized array: 1 2 3 4 5

Memory freed successfully

This program teaches you how to use the new and delete operators in C++ for dynamic memory allocation. The new operator allocates memory at runtime and returns a pointer, while delete frees the allocated memory. Proper use of new and delete is essential for managing dynamic memory and preventing memory leaks.


1. What This Program Does

The program demonstrates dynamic memory allocation:

  • Allocating single variable using new
  • Allocating arrays using new[]
  • Initializing allocated memory
  • Freeing memory using delete and delete[]
  • Setting pointers to nullptr after deletion

Dynamic memory allows allocation at runtime when size is unknown at compile time.


2. Header File Used

#include <iostream>

This header provides:

  • cout for displaying output
  • cin for taking input from the user

3. 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


4. Allocating Single Variable

Basic Allocation:

int* ptr = new int(10);

How it works:

  • 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


5. Allocating Arrays

Array Allocation:

int* arr = new int[5];

How it works:

  • 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};

How it works:

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

6. 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


7. Freeing Single Variable

Deleting Single Variable:

delete ptr;

How it works:

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

8. 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

9. 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

10. 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

11. 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

12. return 0;

This ends the program successfully.


Summary

  • new operator: allocates memory dynamically at runtime, returns pointer.
  • delete operator: frees memory allocated by new.
  • For arrays: use new[] to allocate, delete[] to free.
  • Always match new with delete and new[] with delete[].
  • Set pointers to nullptr after deletion to prevent dangling pointers.
  • Understanding new/delete enables dynamic memory management.
  • Essential for runtime-sized data structures and large objects.

This program is fundamental for learning dynamic memory allocation, understanding heap memory, and preparing for advanced memory management and data structures in C++ programs.