The function malloc () of header file <stdlib.h> allocates memory of size (in bytes) expressed as its argument. The return value of malloc () is a void pointer to the first byte of the allocated block of memory. However, if the process of allocation of memory fails due to lack of sufficient memory, or due to some other reason, it returns NULL pointer. The argument of malloc () is the unsigned integer or an expression which evaluates to an unsigned integer. Any program using this function should also have statements which check the return value of the function so that if the memory is not available one can gracefully exit from the program.
Since the function malloc () returns a void pointer, it has to be cast to the type of data being dealt with. The header file <stdlib. h> must be included in the program if you are using malloc (). The prototype of the function is given below.
void* malloc(size_t size);
In the above declaration, size_t is the typedef of unsigned integer number. For allocating memory for variables of types int, double, char etc., we must cast the void pointer returned by malloc ( ) to the 'respective type. For instance, say we want to allocate memory to store n integers in contiguous memory locations like elements of an array, the code may be written as given below.
# include <stdlib.h>
int *ptri ;
ptri = (int*) malloc(n*sizeof(int));
In the above code, the function malloc allocates n*sizeof (int) bytes of memory and returns the value of pointer ptri. For example, the following code will allocate enough memory to store two int numbers. The return value of the function malloc is the value of ptri which is the address of the first byte of the memory block.
Suppose that the system allocates 4 bytes for storing one int number, then for storing 2 int numbers, the above expression will allocate 4 x 2 = 8 bytes of memory and will return the address of the first byte of this chunk of memory. That address would represent the value of pointer ptri. In case the allocation is not successful due to lack of available memory, the return value would be NULL pointer. Therefore,
for the above code the following test should also be included for graceful exit:
if ( ptri == NULL)
printf("Error in memory allocation");
As a second example, let us consider that we need to allocate enough memory to store m double numbers. The code is as below.
double *pd ;
pd= (double*) malloc( m* sizeof(double));
Similarly, we may use this function in creating arrays of structures in linked lists. Suppose, we have structures of the following type:
char Name ;
If it is required to dynamically create n such structures, the memory allocation for the n structures
may be done as follows:
struct student * Pst;
Pst = (struct Student*) malloc( n* sizeof(struct Student));
Illustrates allocation of memory for an array by malloc () .
p = (char*) malloc(8);
cout<<"Memory Allocation Failed";
cout<<"Enter a String: ";