Dynamic Memory Allocation in C++ | Types Of Memory

Dynamic Memory Allocation | Techmenology

Dynamic Memory Allocation

In this type of Allocation (Dynamic Memory Allocation), You can control the exact size and the lifetime of these memory locations.The most amazing benefit of Dynamic Memory Allocation is that if you declare a memory location, the memory will not be reserved until you assign some memory to it.This is also called Run time memory allocation.As the fate of the memory is decided at Run time.After you use that memory in your program you must free it .If you don’t free it, you’ll run into memory leaks, which may cause your application to crash, since at some point of time, system cannot allocate more memory. There are different methods in different programming languages.Here is an example of Dynamic Memory Allocation using new keyword.

Code

#include <iostream>
#include <string>

using namespace std;

int main () {
int* ptr;
ptr = new int;
*ptr=10;
cout <<*ptr;
delete ptr;

return 0;
}

Explanation

  1. To allocate memory for a data type you must create an pointer of same data type.
  2. Then the desired memory of a Data type is declared and it’s address is given to the already created pointer. Or you can say that the pointer will point to the newly allocated dynamic memory location using new keyword.
  3. If you run the code now, the memory won’t  be used for this memory location until you assign some data to it.
  4. Now if the data is assigned you can perform the desired operation with data using pointer.
  5. Now the data is useless after using it. We must free it to avoid the system crashes and other abnormalities by using delete  keyword.

Static Memory Allocation

In Static Memory Allocation the memory for your data is allocated when the program starts. The size is fixed when the program is created. It applies to global variables, file scope variables, and variables qualified with static defined inside functions.

Code

#include <iostream>
#include <string>

using namespace std;

int main () {
int var=10;

return 0;
}

Explanation

In this type of allocation, you strictly allocate memory for your data at compile time. This is also called simple memory allocation. It is mostly used and very easy to application.

 

One Comment

Add a Comment

Your email address will not be published. Required fields are marked *