Often some situation arises in programming where data or input is dynamic in nature, i.e. the number of data item keeps changing during program execution. A live scenario where the program is developed to process lists of employees of an organization. The list grows as the names are added and shrink as the names get deleted. With the increase in name the memory allocate space to the list to accommodate additional data items. Such situations in programming require which technique. Explain the concept with the help of suitable examples
Such situations require dynamic memory management techniques. In this case, dynamic memory allocation should be used.
Dynamic memory allocation is where the memory is allocated at runtime and the allocation of memory space is done dynamically within the program. Programmers can dynamically allocate storage space while the program is running, but they cannot create new variable names. Therefore dynamic allocation requires two criteria; creating the dynamic space in memory and storing its address in a pointer.
Memory de-allocation is performed by the programmer where the clean-up of space is done for variables or other data storage. For de-allocating dynamic memory, delete operator is used.
Example
#include <iostream>
using namespace std;
int main () {
double* x = NULL; // Pointer initialized with null
x = new double; // Request memory for the variable
*x = 78.95; // Store value at allocated address
cout << "Value of x : " << *x << endl;
delete x; // free up the memory.
return 0;
}
Comments
Leave a comment