All about “new” operator in C++

new operator in c++

Sometimes in the project, we have to require a dynamic size buffer to store the data at run time. Data size could be dynamic and length could change as per the situation that means, we are not aware in advance how much memory we would need to store data in a buffer.

In one of my projects, we had to upgrade the firmware of the device using the USB communication in which we only had a text file which contained the firmware (.hex) of the device. The size of the firmware (.hex file) can be dynamic it depends on the requirement, we had to read hex data from the text file and stored in a buffer.

Here problem is that length of the buffer because we don’t know the size of the text file because it is totally dynamic. So we cannot create the fixed length buffer because it can be dangerous. Here our requirement is that to create a dynamic length buffer whose size could be changed as per the requirement and situation.

So here a question comes, how to make the length of the buffer dynamic? or in other words how to allocate the memory to the buffer at the run time?

It is a very simple question and the answer of this question is the dynamic memory allocation. But again one question comes what provides the memory at run time, so the answer to this question is the heap.

The heap memory (or free store in c++) has the ability to provide the memory at run time using a special operator in C++ which returns the address of the allocated space. This operator is called new operator.

If you don’t need the allocated memory anymore, you can free it using the delete operator, which de-allocates the allocated memory.

So in this article, I will discuss to how to allocate memory at the run time and how the new and delete operator allocate and deallocate memory in C++.

new operator

There are following generic syntax to use the new operator to allocate memory for any data-type.

Here, data-type could be any built-in data type ( int, char, double, float) or user defined data type (structure or class) including an array. If new fail to return the valid memory address then it returns NULL or the exception.

What is the requirement of dynamic memory allocation?

Let us take an example where we will take an integer pointer and try to assign the value and see what happened?

Your program compiles perfectly but when you trying to run your program it will crash because pointer has no valid address. The pointer behaves here like the wild pointer.

So to resolve this problem we will request the memory for it at the execution time using the new operator.

delete operator in c++

After using the dynamically allocated memory we have to delete the memory because it is not deleted by the compiler automatically. So if we forget to delete the memory than we will get memory leak issues in the program.

delete operator syntax

There is following generic syntax to use delete operator to free the allocated memory.

For the better understanding let’s take an example.

Dynamic memory allocation for an array

I have already discussed at the beginning of the article, we can also allocate a block of memory using the new operator in c++.

In below example, I am allocating memory for a character array and giving the size of the array is 10 that means it can store 10 characters.

See the below example

We can also create a multidimensional array using the new operator. In the below example I am creating a 2D array has 3 row and 3 column with the help of double pointer and new operator.

How to initialize the array with default (0) value in c++

Each element of a “T” type array can be initialized with 0 using the empty parenthesis. This is explicitly permitted by ISO C++ 03.

Create class object using the new operator in c++

In c++ we can also create the object using the new keyword. Let see the below example where I am creating an Animal class object using the new keyword.

Why used new operator in c++

Below I am describing some points which describe why we are used new operator in c++.

  • When we create an object using the automatic storage class than it destroys automatically when we go beyond the scope in which it declares. Let’s take an example for the better understanding.

But when trying to access the cat object beyond its scope then gets the compiler error.

We can solve the above problem to create the object using the new operator because memory which allocated by the new does not destroy automatically when goes beyond the scope. It is the responsibility of the developer to destroy the allocated memory explicitly using the delete operator.
Here one thing needs to remember, define pointer with a suitable scope to access the allocated memory.

  • The new operator does not only resolve the scope problems but it also resolves the array size problem that means we can create an array with dynamic size using the new keyword.
  • A stack memory has a limited size so if we create all the object in the stack memory then might be there are chances to get the stack overflow. So to prevent from the stack overflow we have to also use the dynamic memory in our program
  • When we are allocated the memory for the class object using the new operator then the constructor of the class also execute to initialize the member of the class.

Let’s see the below example.

Exception handling of new operator

When new operator request for the memory then if there is a free memory is available then it returns valid address either it throws bad_alloc exception.

Let’s see an example where we will catch the bad_alloc exception through try catch block.

To avoid the exception throw we can use “nothrow” with the new operator. When we are used “nothrow” with new operator then it returns a valid address if it is available either return 0 (NULL).

But here one point need to remember we need to include file <new> for the use of “nothrow” with the new operator.

What is the difference between new operator and malloc?

In below section, I am describing some differences between the malloc and new.

                        malloc                     new
malloc is a library function. new is an operator.
It does not call the constructor.It calls the constructor.
It returns the void * if memory is availableIt returns exact data type if memory is available.
It returns NULL on failure.It throws bad_alloc exception on failure.
It cannot be overridden.It can be overridden.
In which memory allocated from the heap.Here memory allocated from the free store.
Need to pass the size.Size is calculated by the compiler.

Leave a Reply