Dynamic memory allocation
Dynamic memory allocation
refers to the method of allocating a block of memory and releasing it when the
memory is not required at the time of running the program. A block of memory
can be used to store values of simple or sub scripted variable and a block of
memory can be accessed using a pointer. Malloc(), calloc(), realloc() are the
function used in dynamic memory allocation and this function are available in
the header file <alloc.h>. when we have to dynamically allocate memory
for variables in our programs then pointers are the only way to go. When we use
malloc() for dynamic memory allocation then you need to manage the memory
allocated for variables yourself.
malloc():- malloc() is used to allocate a single memory
block memory to store value of specific data type.
Syntax of malloc(): - pointer variable name=(type *)malloc(size);
Example: -
ptr=(int*)malloc(100);
ptr= (int*) malloc(size of
(int));
calloc(): - calloc() function
used to allocate memory in multiple blocks of same size during the program
execution space allocated is used to store values of an array or structure.
ptr = (type*) calloc(n,m);
n = number of block to be
allocated
m = number of bytes in each
block of memory.
realloc(): - realloc()
function is used to modified or reallocated the memory space which is
previously allotted. This facilate to increase or reduced the allotted space at
a late stage in a program.
ptr = realloc()
Free() function: - it is used
to release the memory space which allotted using malloc() or calloc() or
realloc(). When this function is executed ,allotted blocks of memory are
released.
DIFFERENCE
BETWEEN STATIC MEMORY ALLOCATION AND DYNAMIC MEMORY ALLOCATION IN C:
Comments
Post a Comment
please subscribe my blog and let me suggest how I improve this site