7. Dynamic Memory Allocation in C++.
Hello folks!
Welcome to this blog
series. In
the previous blog we have studied different type of memory allocation. Now in this blog we will see how Dynamic
memory is
allocated
in C++
Dynamic memory allocation in C++ :
In C++ all the functions
related to dynamic memory allocation are present in the “cstdlib” library.
Also, C++ provides additional dynamic memory allocation operators like ‘new’
and ‘delete’ operators in the “iostream” library. The following is syntax of
new and delete operators for allocating memory for variable and array
respectively.
new data-type;
new data-type[size];
delete variable-name;
delete[] variable-name;
The ‘new’ operator
basically returns and address to memory location which needs to be stored in a
pointer type of variable of the same data type. Other functions present in the
“cstdlib” library are malloc(), calloc(), realloc(), free.
malloc()
function:
‘malloc’ stands for
memory allocation. The malloc() function reserves a block of memory of the
specified number of bytes and it returns a pointer of void which can be casted
into pointers of any form. The syntax for malloc() is
(castType*)malloc(size)
calloc()
function:
The name ‘calloc’ stands
for contiguous allocation. The malloc() function allocates memory and leaves
the memory uninitialized. Whereas, the calloc() function allocates memory and
initializes all bits to zero. The syntax for calloc() is
(castType*)calloc(n, size)
realloc()
function:
‘realloc’ or
‘re-allocation’ function is used to dynamically change the memory allocation of
a previously allocated memory. In other words, if the memory previously
allocated with the help of malloc() or calloc() is insufficient, realloc() can
be used to dynamically re-allocate memory. The syntax for realloc() is
realloc(ptr, newSize)
free()
function:
‘free’ method is used to
dynamically de-allocate the memory. The memory allocated using functions
malloc() and calloc() is not de-allocated on their own. Hence the free() method
is used, whenever the dynamic memory allocation takes place. It helps to reduce
wastage of memory by freeing it. The syntax for free() is
free(ptr)
Below are few screenshots of the code for our system
in which we have used these dynamic memory allocation concepts.
So this is all about dynamic memory allocation in C++. In the next blog we will discuss about the basics of file handling in C++.
References :
By-
Ashutosh Bardapurkar (k-05)
Hrishikesh Deshpande (k-16)
Archit Hiwrekar
(k-23)
Chinmay Kapkar (k-33)
Impressive
ReplyDeleteNicely explained!!
ReplyDelete