Dynamic Memory Allocation in C


Most commonly used dynamic memory allocation functions:

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.

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. 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.

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.