Dynamic Memory Allocation (DMA):
Many
languages permit a programmer to specify an array’s size at run time. Such
languages have the ability to calculate and assign memory spaces required by
the variable during run time (execution) of program. The process of allocating
memory at run time is known as Dynamic Memory
Allocation. In C, there are four library functions (routines) known as “Memory Management Functions” that can be used for
allocating and freeing memory during program execution. We required a header
file “stdlib.h” for using DMA functions in the
program.
Required
functions: malloc( ), calloc( ),
realloc( ), free( ).
malloc( ) :- This function is
used to allocate requested size of bytes and returns a void
pointer to the first byte of the allocated space. We can assign it for
any type of pointer.
Syntax:
ptr=(cast-type *) malloc( byte-size);
intPtr=(int *) malloc(5 * sizeof(int)); => allocating 10 bytes for integer.
chPtr=(char *) malloc(12); => allocating 12
bytes for character.
calloc( ) :- This function is
used to allocate requesting memory space at run time for storing derived data
types such as arrays and structures. While malloc( ) allocates a single block of storage space, calloc( ) allocates multiple blocks of storage of same size. Initializes
all the bytes to zero and then returns a pointer to the memory.
Syntax:
ptr=(cast-type *) calloc( n, element-size);
free( ) :- When we no longer
need the data stored in a previously allocated memory space, then we can free that memory space dynamically at run time using
this function. Here “ptr” is a pointer to a memory block which has already been
created by malloc or calloc.
Syntax:
free(ptr);
realloc( ) :- It is also
possible that we can increase or reduce memory size created by malloc function. realloc( )
function is used to modify the size of
previously allocated spaces. This process is called the reallocation of memory.
Syntax:
ptr=(cast-type *) malloc(size);
ptr=realloc(ptr, new-size);
~~~~~~@~~~~~~
No comments:
Post a Comment