Dynamic memory allocation in C++There are times where the data to be entered is allocated at the time of execution. For example, a list of employees increases as the new employees are hired in the organization and similarly reduces when a person leaves the organization. This is called managing the memory. So now, let us discuss the concept of dynamic memory allocation. Memory allocation Reserving or providing space to a variable is called memory allocation. For storing the data, memory allocation can be done in two ways -
Why Dynamic memory allocation? Dynamically we can allocate storage while the program is in a running state, but variables cannot be created "on the fly". Thus, there are two criteria for dynamic memory allocation -
Similarly, we do memory de-allocation for the variables in the memory. In C++, memory is divided into two parts -
Dynamic memory allocation using the new operator To allocate the space dynamically, the operator new is used. It means creating a request for memory allocation on the free store. If memory is available, memory is initialized, and the address of that space is returned to a pointer variable. Syntax Pointer_variable = new data_type; The pointer_varible is of pointer data_type. The data type can be int, float, string, char, etc. Example int *m = NULL // Initially we have a NULL pointer m = new int // memory is requested to the variable It can be directly declared by putting the following statement in a line - int *m = new int Initialize memory We can also initialize memory using new operator. For example int *m = new int(20); Float *d = new float(21.01); Allocate a block of memory We can also use a new operator to allocate a block(array) of a particular data type. For example int *arr = new int[10] Here we have dynamically allocated memory for ten integers which also returns a pointer to the first element of the array. Hence, arr[0] is the first element and so on. Note
Code Now as we have allocated the memory dynamically. Let us learn how to delete it. Delete operator We delete the allocated space in C++ using the delete operator. Syntax delete pointer_variable_name Example delete m; // free m that is a variable delete [] arr; // Release a block of memory Example to demonstrate dynamic memory allocation Output Value of m: 29 Value of f: 75.25 Value store in block of memory: 1 2 3 4 5 Next TopicFast input and output in C++ |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India