Explore All About New/Delete Operators In C++.
We have already seen variables and static arrays in C++ in our earlier tutorials.
As far as the memory allocated to the variables and arrays is concerned, it is the static memory that is allocated by the compiler depending on the data type (in case of variables) and dimensions provided for arrays.
The memory allocated by the compiler is allocated on the stack. But in most cases, we may not be aware of the exact amount of the memory we need.
=> Read Through The Popular C++ Training Series Here.
What we would do is allocate and de-allocate as much memory as we want and also as and when we want it. This is done by dynamically allocating the memory. In contrast to static allocation, dynamically allocated memory is allocated on the heap.
Dynamic memory allocation is useful as we can allocate variable size memory which we cannot achieve with the compiler allocated memory. We have the flexibility of allocating memory when we need and de-allocate it when we don’t need it.
But apart from these uses, we also have to keep in mind that in case of dynamically allocated memory, it’s the user’s responsibility to de-allocate the memory. If we forget to de-allocate the memory, then it causes a memory leak wherein the memory is not deallocated until the program terminates.
This might result in too much memory being used and thus causes serious bottlenecks.
Table of Contents:
Dynamic Memory Allocation
C language uses ‘malloc’,’calloc’ and ‘realloc’ functions to allocate memory dynamically. To de-allocate the memory allocated dynamically with these functions, it uses ‘free’ function call. C++ language also supports these functions from the C language to allocate/de-allocate memory.
Apart from these functions, C++ introduces two new operators which are more efficient to manage the dynamic memory. These are ‘new’ operator for allocating memory and ‘delete’ operator for de-allocating memory.
In this tutorial, we will learn more about new and delete operators in C++ language.
The “new” Operator
The “new” operator allocates memory for a variable or any other entity on a heap.
The general syntax of the “new” operator is:
pointer_variable_of_data_type = new data type;
The data type mentioned above can be any valid data type supported by C++. It can be a built-in datatype or any user-defined data type including classes and structures.
For Example,
int *ptr = NULL; ptr = new int();
In the above example, we have declared a pointer variable ‘ptr’ to integer and initialized it to null. Then using the “new” operator we allocate memory to the “ptr” variable. If memory is available on the heap, the second statement will be successful. If no memory is available, then the new operator throws “std::bad_alloc” exception.
Hence it is a better idea to check if the memory is allocated successfully by the new operator before using this variable or entity in the program.
We can also initialize variables using the new operator as follows:
ptr = new int(10);
In the above example, the pointer variable “ptr” is the allocated memory using the new operator and at the same time, the assigned value is 10. This is yet another way of initialization in C++.
Using The “new” Operator With Arrays
Yet another use of the “new” operator is allocating memory for arrays. Here we specify the number of elements to be allocated for the array.
An Example of allocating array elements using “new” operator is given below:
int* myarray = NULL; myarray = new int[10];
Here, new operator allocates 10 continuous elements of type integer to the pointer variable myarray and returns the pointer to the first element of myarray.
The Delete Operator
The memory allocated dynamically using the new operator has to be freed explicitly by the programmer. For this purpose, we are provided with the “delete” operator.
The general syntax of the delete operator is:
delete pointer_variable;
So we can free the memory allocated to the ptr variable above as follows:
delete ptr;
This statement frees the memory allocated to the variable “ptr” back to the memory pool.
We can also use the delete operator to free the memory allocated to arrays.
For Example, the memory allocated to the array myarray above can be freed as follows:
delete[] myarray;
Note the subscript operator used with the delete operator. This is because, as we have allocated the array of elements, we need to free all the locations.
Instead, if we had used the statement,
delete myarray;
We know that myarray points to the first element in the array, so the above statement will only delete the first element of the array. Using subscript “[]”, indicates that the variable whose memory is being freed is an array and all the memory allocated is to be freed.
The below programming Example shows the usage of new and delete operators in C++.
// Example program #include <iostream> #include <string> using namespace std; int main() { int *ptr = NULL; ptr = new int(); int *var = new int(12); if(!ptr) { cout<<"bad memory allocation"<<endl; } else { cout<<"memory allocated successfully"<<endl; *ptr = 10; cout<<"*ptr = "<<*ptr<<endl; cout<<"*var = "<<*var<<endl; } double *myarray = NULL; myarray = new double[10]; if(!myarray) {cout<<"memory not allocated"<<endl;} else { for(int i=0;i<10;i++) myarray[i] = i+1; cout<<"myarray values : "; for(int i=0;i<10;i++) cout<<myarray[i]<<"\t"; } delete ptr; delete var; delete[] myarray; return 0;
Output:
memory allocated successfully
*ptr = 10
*var = 12
myarray values : 1 2 3 4 5 6 7 8 9 10
The screenshot for the same is given below.
In the above code example, we have demonstrated the usage of new and delete operators. We have used the “new” operator to allocate memory for a variable, arrays and as well as initialize another variable with a value. Then we delete these entities using the delete operator.
Conclusion
This is all about the new and delete operators of C++ as far as standard data types are concerned. We can also use new and delete operators for user-defined data types as classes and structures.
We will learn more about the usage of these operators for creating objects when we learn object-oriented programming using C++.
=> Take A Look At The C++ Beginners Guide Here.