Dynamic Memory Allocation in C++

As we are already aware of the C functions such as Malloc(), Calloc() and realloc() that are used to dynamically allocate memory from the heap, In C++ programming language these Dynamic memory Allocations are made very simpler.


 


Int*q= new int[200];

Here, this syntax will allocate memory space of 200 integers from the heap. As we are already aware of Memory Structure in c programming language where there is Code Segment, Data Segment, Heap and Stack.

memory allocation

The stack is used for storing local variables, Data section is used for global types of variables and the function of Heap in c++ is identical as in c for allocating Dynamic Memory.

In the given syntax, there is new int [200], which means that it needs a block of memory to store 200 integers from Heap. Let suppose 1000 will be starting address of the memory. This address will be returned and assigned to q, q will store the return address i.e. 1000.

This is the syntax to dynamically allocate memory in C++ where you can use any variable name such as m or n for eg. You can use m,in place of 200 and use the statement cin>>m;

Int*q= new int[200];

or

Int*q= new int[m];

In another example

Char*b= new char [40];

This statement means that it wants the memory of 40 characters to store memory dynamically from heap as explained in the previous example starting address will be returned to b, and it will store that starting address.

This statement in c language is equivalent to

Char*b=(char*) malloc(sizeof(char)*40); where malloc, calloc and realloc functions returnĀ  void*,Typecasting of specific kind of pointer is required before assigning. This process is not required in c++ because in c++ while allocating memory we are also mentioning the datatype in the syntax as in statement it eliminates the requirement of defining size of and typecasting. The syntax itself determines that you need m no of space for memory allocation.

Int*q= new int[m];

CC++
Char*b=(char*) malloc(sizeof(char)*40);Char*b= new char [40];

How to deallocate the memory in C++

In c++, there is a Delete keyword that is used to deallocate memory.

Delete b; (only delete the memory of one character) this statement can be used to deallocate the memory where there is a requirement of deleting the memory of one character as in the example

Char*b = new char;

Delete[] b; it free all the memory that is made up of more than one character.

Memory leakage

Delete b;Delete[] b;
If, the Delete C; is used. It will erase only the first character of the memory block of 40 If, the Delete c; is used. It will erase only the first character of the memory block of 40 characters which results in memory leakageIf this syntax with subscript is used, that will erase all the memory block of 40 characters, which will free all the memory and help to prevent memory leakage

Leave a Reply

avatar
  Subscribe  
Notify of