Pointers II-197
Here, in this declaration, 20 bytes are allocated to pointer variable pnt of type int and base
address is returned to pointer pnt.
2. free() function: It is used to release the memory allocated by memory allocating functions.
Thus, by using this function, the wastage of memory is prevented. The declaration of the function
is as follows:
free (pnt)
In the above declaration, pnt is a pointer. The free() function releases the memory occupied by
the pointer variable pnt.
30. Explain the concept of dynamic memory allocation.
Ans: There is a technique by which a program can obtain space in the main memory at run time that
is called dynamic allocation. Dynamic allocation is a technique in which a program can acquire storage
space in the main memory. In this method, the space for the program is allocated from the free space
during the execution of the program. The free region of the memory is called the heap. Depending upon
the memory model, the portions of the heap are allocated for memory requirement. Conceptually, the
C programs are stored in the free space from the heap. The amount of memory requirement is decided
by how the program is designed. For example, if a program is developed with many recursive functions,
then this is implemented with stack.
31. Describe the various functions used for memory allocation.
Ans: The various functions that are used for memory allocation are malloc, calloc, free,
realloc and coreleft.
For malloc and free functions, refer the answer to the question 19.
1. calloc()function: It is useful for allocating multiple blocks of memory. It is declared with
two arguments. The prototypes are declared in alloc.h and stdlib.h. The format of the
calloc() function is as follows:
pnt = (int *) calloc (4,2);
The above declaration allocates four blocks of memory; each block contains 2 bytes. The base
address is stored in the integer pointer. This function is usually used for allocating memory for
array and structure.
2. realloc()function: It reallocates main memory. The prototypes are declared in alloc.h and
stdlib.h. Attempts are made to shrink or enlarge the previously allocated memory by malloc() or
calloc() functions. It returns the address of the reallocated block, which can be different from
the original address. If the block cannot be reallocated or size == 0, realloc() returns NULL.
The syntax of the function is as follows:
ptr = (type *) realloc (ptr, new size);
3. coreleft function: It returns a measure of unused memory. If the memory model selected is tiny,
small or medium, then follow the function declaration as per statement (a). If the memory model
selected is compact, large or huge, follow the declaration (b).
(a) unsigned coreleft(void);
(b) unsigned long coreleft (void);
M09_ITL-ESL4791_02_SE_C09.indd 197 12/22/2012 5:04:02 PM