For the execution of a program, it is essential to bring the program into the main memory. When a program does not fit into the main memory, parts of it are brought into the main memory one by one and the full program is executed eventually.
There are two techniques used for storing the information of C programs in the "main memory". The first technique involves storing global and local variables, which are fixed during compilation and remain constant throughout the run time of the program. Space for the local variable is allocated from the STACK each time when the variable comes into existence. Also known as Static Memory Allocation (SMA).
The second technique by which a program can obtain memory space in the main memory is with dynamic allocation. Also known as Dynamic Memory Allocation (DMA).
The method of allocation of memory at the time of execution of a program is called dynamic memory allocation.
DYNAMIC MEMORY ALLOCATION FUNCTIONS:
The malloc() Function:
The malloc() function is used to allocate memory space in bytes to the variable of different data types. The function reserves bytes of determined size and returns the base address to the pointer variable. The return type of malloc() function is a void pointer.
Syntax:
Example:
float *ptr;
ptr = (float*)malloc(sizeof(float));
In C language when we does not convert the void pointer address (which are return by malloc() function) into required pointer then compiler simply displayed a warning message “Non Portable Pointer Conversion” but in C++ it is mandatory to convert otherwise compiler flash an error message. So, it is good practice we always convert the void pointer address into required pointer data type.
The calloc() Function:
The calloc() function is useful for allocating multiple blocks of memory. This function is usually used for allocating memory for array and structure.
Syntax:
Where,
Part1 = Number of Blocks.
Part2 = Size of Each Block.
Example:
int *ptr;
ptr = (int*)calloc(5*sizeof(int));
The free() Function:
The free() function is used to release the memory if not required. Thus, using this function the wastage of memory is prevented.
Syntax:
Programming Examples
void main() |