Skip to main content

Dynamic memory allocation with new and delete

Short answer

Dynamic memory allocation uses new to obtain heap memory at runtime, and delete to release it. For a single variable: int *p = new int; delete p; For an array: int *a = new int[n]; delete[] a; The program reads n, allocates an array, computes sum, and frees memory.

What is dynamic memory allocation? Explain how memory is allocated and deleted dynamically for a normal variable and for an array in C++ with example program.

Dynamic memory allocation means allocating memory at run time from the free store (heap) while the program is running, instead of at compile time. In C++ the operator new allocates memory and the operator delete releases it. The amount of memory can be decided by the user during execution, and the memory stays until it is deleted.

For a normal variable

int *p = new int;      // allocate one int
*p = 25;
delete p;              // release it

new int(25) allocates and initialises in one step.

For an array

int *a = new int[n];   // allocate n ints
delete[] a;            // release the whole array (note the [])

If memory is not available, new throws bad_alloc (or returns NULL when nothrow is used).

Example program

#include <iostream>
using namespace std;

int main()
{
    int *p = new int;            // single variable
    *p = 10;
    cout << "Value = " << *p << endl;

    int n;
    cout << "How many numbers? ";
    cin >> n;
    int *a = new int[n];         // array of n elements
    for (int i = 0; i < n; i++)
        cin >> a[i];
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += a[i];
    cout << "Sum = " << sum << endl;

    delete p;                    // free single variable
    delete[] a;                  // free array
    return 0;
}

Note: every new must be matched by a delete, and new[] by delete[], otherwise a memory leak occurs.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 3 questions →