Loading...

Dynamic Memory Management: new and delete

Heap allocations, using new/delete safely, and practices that lead into RAII.

In C++, memory is divided into two main regions: Stack and Heap. While the Stack area is managed automatically, the memory in the Heap is manually controlled by the programmer. Dynamic memory management is used to allocate and release memory during program execution. In this article, we will explore dynamic memory usage in detail using the new and delete keywords.


1. Difference Between Stack and Heap

FeatureStack (Automatic)Heap (Dynamic)
ManagementAutomatic (by compiler)Manual (by programmer)
LifetimeDeleted automatically when function endsRemains until manually deleted
SpeedVery fastSlower (dynamic allocation)
Memory sizeLimitedMuch larger
UsageLocal variablesDynamic objects, arrays

2. Allocating Memory with the new Keyword

The new operator dynamically allocates memory on the Heap and returns the address of the allocated space. This address is usually assigned to a pointer variable.


#include <iostream>
using namespace std;

int main() {
    int *ptr = new int; // allocate memory for one integer
    *ptr = 42;
    cout << "Value: " << *ptr << endl;

    delete ptr; // release memory
    ptr = nullptr; // make pointer safe
}

Note: Memory allocated with new must be manually released with delete. Otherwise, a memory leak will occur.


3. Dynamic Arrays with new

To create a dynamic array, use new[]. The array size can be determined at runtime.


#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "How many elements? ";
    cin >> n;

    int *arr = new int[n]; // create an array of n elements

    for (int i = 0; i < n; i++)
        arr[i] = (i + 1) * 10;

    cout << "Array: ";
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";

    delete[] arr; // release memory
    arr = nullptr;
}

Using delete[] is crucial; the regular delete is only for single variables and not for arrays.


4. Steps of Dynamic Memory Allocation and Deallocation

  1. new → Allocates memory on the Heap.
  2. Pointer → Stores the address of the allocated memory.
  3. Data is processed or filled.
  4. delete / delete[] → Frees the allocated memory.
  5. Pointer = nullptr → Prevents dangling pointers.

5. What is a Memory Leak?

If dynamically allocated memory is not released, unused memory blocks accumulate over time. This situation is called a memory leak and can cause serious performance problems in long-running programs.


void BadExample() {
    int *p = new int(10);
    // delete p; // Forgot! Memory leak
}

Solution: Always use delete to release memory.


6. nullptr and Memory Safety

Before C++11, null pointers were usually represented by NULL. In modern C++, the type-safe keyword nullptr should be used instead.


int *p = nullptr;

if (p == nullptr) {
    cout << "Pointer is not pointing to any address." << endl;
}

Using nullptr helps prevent invalid memory access and segmentation faults.


7. Using Dynamic Memory with Functions

Memory can be dynamically created and passed to functions. This technique is especially useful when working with dynamic arrays.


void Fill(int *p, int n) {
    for (int i = 0; i < n; i++)
        p[i] = (i + 1) * 2;
}

int main() {
    int *arr = new int[5];
    Fill(arr, 5);

    for (int i = 0; i < 5; i++)
        cout << arr[i] << " ";

    delete[] arr;
}

8. Creating Objects with new

The new operator can also be used to create class objects, not only basic data types.


#include <iostream>
using namespace std;

class Student {
public:
    string name;
    Student(string n) : name(n) {
        cout << name << " created." << endl;
    }
    ~Student() {
        cout << name << " deleted." << endl;
    }
};

int main() {
    Student *p = new Student("Ali");
    delete p; // destructor is called
}

Deleting an object created with new automatically calls its destructor.


9. Smart Pointers (Modern C++ Approach)

Starting with C++11, smart pointers were introduced as an alternative to manual delete operations. They provide automatic memory management.


#include <iostream>
#include <memory>
using namespace std;

int main() {
    unique_ptr<int> p = make_unique<int>(100);
    cout << *p << endl; // 100
}

Smart pointers automatically release memory when the object goes out of scope, eliminating the risk of memory leaks.


10. TL;DR

  • new → Allocates memory on the Heap and returns its address.
  • delete → Frees memory (single variable).
  • new[] / delete[] → Used for dynamic arrays.
  • nullptr → Safe representation for null pointers.
  • Each new must have a corresponding delete to prevent memory leaks.
  • std::unique_ptr and std::shared_ptr are modern alternatives.
  • All examples can be compiled in Visual Studio 2022 or GCC 11+.

Related Articles