Dynamic Memory Allocation
Every Data or Instruction to be processed must be loaded into internal memory before its processing takes place. This process is called Memory allocation. These are of two types: Static and Dynamic Memory Allocation.
First let’s talk about Static memory allocation. Here we reserve a certain amount of memory by default inside our program to use for variables, etc and this static memory is allocated during the compilation of the Program. Once we reserve this memory, no other program can use it, even if we are not using it at the time.
But many times we are not aware in advance about how much memory we will need to store particular information in a defined variable. The size of required memory may be determined only during the run time , i.e. when the program is being run.
Here Dynamic memory comes into play. By using Dynamic memory allocation, the programmer can allocate memory to a program during run time. The program uses its allocated memory only when it is active. In its inactive state, the program will use much less memory, hence allowing other programs to take up the unused memory. You can even de allocate memory so as to free up memory for other programs, but we need to do this manually.
In C++, an operator called new is used for Dynamic memory allocation. To allocate a single variable dynamically, we use the following syntax:
int *data = new int; // dynamically allocate an integer named data.
The new operator returns the address of the variable that has been allocated. This address can be stored in a pointer, and the pointer can then be dereferenced to access the variable.
int *data = new int; // dynamically allocate an integer
*data = 7; // assign 7 to this integer
When we are done with a dynamically allocated variable, we need to explicitly tell C++ to free the memory for reuse. This is operation is done via the scalar (non-array) form of the delete operator:
delete data; // deallocate memory...
Please join StudyMode to read the full document