Dynamic Memory allocation in C++ (new and delete operators)

Aug 14, 2018

One of the crucial part of any kind of computer programming is the memory management. In some of the small or short programs, the effect of sporadic memory management does not seem to have an effect because of the larger memory available in todays computers. But as the program grows larger the effect comes into play.

  Basically, the memory for the variables in a program can be allocated in two ways. One is statically, it means during the program compilation the memory is allocated or the amount of memory is known at compile time and allocated. Another one is dynamically, it means during the program run time the memory is allocated or the amount of memory is known at run time and allocated.

  The normal variable declaration and array declaration in C++ is static memory allocation. The amount of memory required for the program is pre-allocated. For array declaration, for example if we declare 50 character array then we can use optimum of 50 character of an array. What if we want to use more than 50 charaters, there is no way that we can use more than 50 characters for the same array. And the another case what if we use only 20 charaters of the array, definately the memory allocated for 30 characters will be wasted. So, such type of memory allocation seems to be tedious though the case is good for the fixed type of the memory allocation. To overcome such type of problems Dynamic memory allocation DMA  comes into existance. DMA  helps for easier memory menagement. It faciliates us to allocate memory as per our requirements at runtime. For example, if we want to write a program that ranks the students based on the marks obtained by the students then in that scenario we don't have the information that how many students will be there for the processing, the memory allocation for the students must be done dynamically.

  In C++, there are two operators available for the dynamic memory allocation and de-allocation; The new operator for allocation and delete  for the de-allocation.

I) new operator

  The new operator in C++ faciliates for dynamic memory allocation similar to malloc() and calloc() in C. It retrives memory at runtime from the memory heap from OS and returns the address.

The syntax is as follows.

data_type *pointer_variable; //pointer variable declaration

pointer_variable = new data_type; //allocate space for single variable

pointer_variable = new data_type[SIZE]; //allocate memory for  an array of size SIZE

For example:

float *float_ptr; //pointer variable declaration 

float_ptr = new float; //allocates memory for single variable

float_ptr = new float[10]; //allocates memory for array of floating type of size 10

also we can directly write, 

float *fptr = new float[10]; //allocation for floating type array of size 10

float *fptr = new float(10); //allocates for the single floating type variable and initializes the value to 10 

 

Similarly for the multi dimeansional array,

int *twoD;

twoD = new int[m][4];

int *threeD;

threeD = new int[m][4][5];

it means first index can be either variable or constant but other should be constant.

 

II)delete operator

The memory allocated during runtime by new operator is reserved even after the variable scope ends or the variable is not needed. There can be lots of memory allocations as the program runs on. So, as we go on allocating memory for variables and leaves them unused, the program may run out of memory and can cause serious problems in the programs. For efficient program to write we need to free the allocated memory for the unused variables which is called memory de-allocation.

  In C++ delete  operator releases the memory from the memory heap that are allocated by new  operator. So the released memory can be reused after then.

The syntax for delete operator:

delete pointer_variable; //deletes or releases single dynamic variable 

delete [] pointer_variable; //deletes or releases dynamically created array

For Example:

float *float_pointer;

float_pointer = new float(10);

.........................................

delete float_pointer;

 

EXAMPLE:

// program to dynamically read the numbers and find the sum

#include<iostream>
using namespace std;

int main(){
	float *float_pointer; //pointer to hold the array
	float SUM = 0;
	int NUMBER;
	cout<<"Enter the total numbers:"<<endl;
	cin>>NUMBER;
	float_pointer = new float[NUMBER];	//allocating memory for array
	cout<<"Enter all the elements:"<<endl;
	for (int i = 0; i < NUMBER; i++)
	{
		cin>>float_pointer[i];
	}
	for (int i = 0; i < NUMBER; i++)
	{
		SUM += float_pointer[i];
	}
	cout<<"TOTAL SUM ="<<SUM<<endl;
	delete [] float_pointer;
	return 0;
}

 

 SAMPLE RUN:

Enter the total numbers:

3

Enter all the elements:

2.3

3.3

3.3

TOTAL SUM =8.9

 

 

Related


16 Default arguments in C++
Date: Sep 2, 2018
17 Friend Function, Friend class
Date: Sep 4, 2018
18 What are friend functions ? Is it possible for a function to be friend of two classes ? If yes then how is it implemented in C++. Explain with suitable example. ---PU-2016 (New Course)
Date: Sep 10, 2018
19 Write an OOP to add two complex numbers using passing objects as arguments. ---PU_2015
Date: Sep 10, 2018
20 Write a Program to add two complex numbers using friend function. ----PU_2015
Date: Sep 10, 2018
21 What are constructors and destructors ? Write a Object Oriented Program to display Fibonacci series (Use constructor for initialization) ----PU-2014
Date: Sep 15, 2018
22 Write a OOP to create a class named "Time" with data members 'hour' and 'minute' a constructor to initialize............. ---PU-2011
Date: Sep 15, 2018
23 What is "this" pointer ? Illustrate with example.
Date: Sep 15, 2018
24 Write a program to create class “Counter” having integer data member, overload the post increment, post decrement, pre increment and pre decrement for the class “Counter”.
Date: Sep 15, 2018
25 Write a Program to overload the unary minus operator using friend function.
Date: Sep 15, 2018
26 Write a OOP to overload "==" operator to determine the equality of two fractional numbers (fractional numbers must be in terms of numerator and denominator)
Date: Sep 15, 2018
27 Write a program to create classes “Dollar” and “Rupee”. Write conversion routine to convert dollar to rupee (1 dollar = 108 rupees).
Date: Sep 15, 2018
28 Write a Program to convert angle in degree to angle in radian. where, angle in radian = angle in degree * PI/180. Use Conversion routine in source class.
Date: Sep 15, 2018
29 Write a program which asks file name from keyboard, opens a file with that name for output, reads the line from keyboard character by character and writes the line onto the file.
Date: Sep 22, 2018
30 WAP to to read the text from the file named "hello.txt" to the file name called "test.txt".
Date: Sep 22, 2018

Tools/Apps





© Nepal Exchange Rates