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() |
Thank you so much for taking the time to read my Computer MCQs Section carefully. Your support and interest mean a lot, and I truly appreciate you being part of this journey. Stay connected for more insights and updates! If you'd like to explore more tutorials and insights, check out my YouTube channel.
Don’t forget to subscribe and stay connected for future updates.