+1 vote
in Class 12 by kratos

What is dynamic memory allocation? Explain the various memory allocation function with its task.

1 Answer

+4 votes
by kratos
 
Best answer

The mechanism of allocating required amount of memory at run time is called dynamic allocation of memory. Sometimes it is required to allocate memory at runtime. When we declare array in any program, the compiler allocates memory to hold the array. Now suppose the numbers of items are larger than the defined size then it is not possible to hold all the elements and if we define an array large enough and data to be stored is less, in that case the allocated memory is wasted leading to a need for dynamic memory allocation. In this mechanism we use a pointer variable to which memory is allocated at run time.

The various memory allocation functions are described below:

(i) malloc( ): It is a memory allocation function that allocates requested size of bytes and returns a pointer to the first byte of the allocated space. The malloc function returns a pointer of type void so we can assign it to any type of pointer. It takes the the following form:

ptr= (cast type *) malloc(byte-size);

where ptr is a pointer of type cast-type. For example, the statement

x=(int ) malloc(10 sizeof(int)) means that a memory space equivalent to 10 times the size of an int byte is reserved and the address of the first byte of memory allocated is assigned to the pointer x of int type.

The malloc function can also allocate space for complex data types such as structures. For example:

ptr= (struct student*) malloc(sizeof (struct student)); where ptr is a pointer of type struct student.

(ii) calloc( ): It is another memory allocation function that allocates space for an array of elements, initializes them to zero and then returns a pointer to the memory. This function is normally used for requesting memory space at run time. While malloc allocates a single block of storage space, calloc allocates multiple block of storage, each of the same size, and then sets all bytes to zero. It takes the following form:

ptr= (cast type *) calloc(n,element-size);

This statement allocates contiguous space for n blocks, each of size element-size bytes.

(iii) realloc( ): realloc is a memory allocation function that modifies the size of previously allocated space. Sometime it may happen that the allocated memory space is larger than what is required or it is less than what is required. In both cases, we can change the memory size already allocated with the help of the realloc function known as reallocation of memory. For example, if the original allocation is done by statement.

ptr= malloc(size);

then reallocation is done by the statement

ptr=realloc(ptr,newsize); which will allocate a new memory space of size newsize to the pointer variable ptr and returns a pointer to the first byte of the new memory block

...