New and Delete Operator in C++

Video Tutorial
FREE
Operators Introduction thumbnail
This video belongs to
C++ Course: Learn the Essentials
14 modules
Certificate
Topics Covered

Overview

C++ allows us to allocate memory for a variable or an array at run time. This is known as dynamic memory allocation. In C++, we need to deallocate the dynamically allocated memory manually after using a variable.We can allocate and then deallocate memory dynamically using the new and delete operators respectively.

Memory Management in C++:

Memory management in C++ is a critical aspect of programming, as it involves allocating and deallocating memory for your program's data and objects. Two primary techniques for memory management are:

Dynamic Memory Allocation:

This involves allocating memory at runtime, using operators like new and malloc to create objects and data structures on the heap. This memory persists until explicitly deallocated using delete or free, which provides flexibility but also requires careful management to avoid memory leaks. In contrast, static memory allocation occurs at compile-time, and memory for objects is determined at the program's design phase. This approach is less flexible as memory usage is fixed but offers performance advantages due to compile-time optimizations.

Applications:

Dynamic memory allocation plays a crucial role in various applications, including:

  • Data Structures: Dynamic memory allocation is vital for creating dynamic data structures like linked lists, trees, and graphs, where the size of the data structure is unknown in advance.
  • Resource Management: It is used for managing resources like files, network connections, and database connections, where the resource's lifetime is not determined at compile-time.
  • Memory Pools: Dynamic memory allocation can be used to create memory pools, improving memory allocation performance in situations with frequent allocations and deallocations.
  • Task Queues: Applications with task queues or job scheduling often require dynamic memory allocation to create and manage task structures dynamically.
  • Object Creation: When the number of objects to be created during program execution varies or is determined at runtime, dynamic memory allocation is essential.
  • Plug-ins and Extensions: Applications that support plug-ins or extensions often use dynamic memory allocation to load and manage external code modules.

C++ New Operator

The new operator in C++ is used to allocate memory for a variable or any other entity like objects or arrays on a heap memory area. If a sufficient amount of memory is available on the heap, the new operator will initialize the memory and return the address of newly allocated memory and you can use pointers to store the address of that memory location.

Syntax for new operator:

Here in above syntax,

  • data_type can be any inbuilt data type of C++ or any user defined data-type.
  • pointer_name is a pointer variable of the type ‘data_type’.

Eg: int* scaler = new int;

In the given example, scaler is a pointer of type int that points to a new memory block created at run time.

What if enough memory is not available in heap:

If sufficient memory is not available in the heap to allocate, it is indicated by throwing an exception of type std::bad_alloc and a pointer is returned unless the exception is handled with a new operator in which case it returns a NULL pointer. So it is good practice to check if new operator is returning NULL pointer and take appropriate action accordingly −

You can initialize the memory using new operator with the following syntax:

Eg: int* scaler = new int(7);

In the above example scaler pointer is pointing to a dynamically allocated variable which is initialized by value 7.

C++ Delete Operator

Since the programmer has allocated memory at runtime, it’s the responsibility of the programmer to delete that memory when not required. So at any point, when programmers feel a variable that has been dynamically allocated is not anymore required, they can free up the memory that it occupies in the free store or heap with the “delete” operator. It returns the memory to the operating system. This is also known as memory deallocation. Also, memory will be deallocated automatically once the program ends.

Syntax for delete operator

Here in above syntax memory has been released which was pointed by pointer_variable

Eg: delete scaler

In the given example, the memory that is pointed by the variable ‘scaler’ will be deallocated.

Note: If the program uses a large amount of unwanted memory using the “new” operator then the system may crash because there will be no memory available. In this case, the delete operator can help the system from crashing or from memory leap.

It is good to use dynamic memory allocation for flexibility and other usages but if the programmer doesn’t deallocate memory, it can cause a memory leak (in which memory is not deallocated until the program terminates). So programmers should carefully explicitly delete the dynamically allocated memory for good coding practice and to avoid memory leak.

C++ “new” & “delete” Operators for Arrays

You can use new and delete operators for dynamic memory allocation and deallocation. Suppose you want to allocate memory for an integer array, i.e., an array of 7 integers.

Using the same syntax that you have used above we can allocate memory dynamically as shown below:

Here in the above example, the pointer ‘scaler’ is pointing to the first element of a dynamically created array of 7 integers.

C++ new and delete operators for arrays

As the programmer has dynamically created the array so to delete that array programmer can use the delete operator as shown below:

Similarly, you can allocate and deallocate memory for a multi-dimensional array.

In the above example, pointer_val is pointing to the memory that has been allocated dynamically to a 7*7 multi-dimensional array of the type int.

The syntax to release the memory for a multi-dimensional array will remain the same as it is for 1-D arrays :

C++ “new” & “delete” Operators for Objects

In C++, you can also dynamically allocate objects. It is just the same as a simple data type. Again use pointers while dynamically allocating memory to objects. You can clarify this concept by taking the example of an array of objects.

In the below example, as you are allocating memory to an array of five Scaler class objects, the constructor of the Scaler class would be called five times. Similarly, while deleting these objects, the destructor will also be called five times.

OUTPUT of the programme:

Example Here is a consolidated example showing all the cases of new and delete operator in C++:

Output of the programme:

The above example shows the usage of new and delete operators on int and float type variables and on arrays.

It’s good to use dynamic memory allocation due to its flexibility and other usages based on programmer requirements, as explained in the above article. So, there are cases where the memory needs of a program can only be determined at runtime. For example, when the memory needs depends on the programmer input. In such types of cases, programmers can use dynamic memory allocation.

Conclusion

In this article, we learned three concepts:

  1. Memory management in C++
  2. new operator for allocating memory dynamically, and
  3. delete operator for deallocating memory

That’s all for now folks!

Thanks for reading.