calloc():
- calloc() stands for contiguous allocation and is also used for allocating a specified number of bytes, given by the number of bytes to allocate and the size of each such object in bytes.
- It is normally used for allocating memory to derived data types such as arrays and structures.
- In the case of calloc() the memory allocated is initialized to 0 unlike malloc() where memory is left uninitialized(garbage values).
- The pointer returned is of type void hence we can typecast such pointer to any type as per to need.
- It returns NULL in case memory is not allocated for some reason.
Syntax:
(void*) calloc (size_t n , size_t size);
Where ‘n’ is the number of blocks to be allocated and size_t is the size of each block(size of each element).
Hence the total number of bytes allocated is (n * size).
Example:
int *ptr = (int*) calloc( 5 , sizeof(int));
The above example allocates a total of 5 blocks where the size of each block is that of type int.
Calloc to allocate memory for structure
#include <stdlib.h> #include <string.h> struct Student { char *name; int roll; float marks; }; int main () { struct Student *stud = (struct Student *)calloc (30, sizeof(struct Student)); if (stud == NULL) printf("\n Memory allocation failed\n"); else { stud->roll = 20; stud->name="techaccess"; stud->marks = 2345.7; printf("\n Name: %s roll: %d marks is: %f \n", stud->name, stud->roll, stud->marks); } return 0; }
Output:
Name: techaccess roll no: 20 marks is: 2345.699951

Application:
Database applications, for instance, will have such a requirement. Proper planning for the values of “n” and “size” can lead to good memory utilization. This is a uniform block of memory of a specific size is achieved with calloc().
Drawback: Size cannot be changed.
Relevant Posts:
- Dynamic Memory Allocation
- malloc()
- realloc()
- free()
- Memory Allocators: brk() and sbrk()
- User defined malloc(), calloc(), realloc() and free()
- Interview questions on dynamic memory allocation
Categories: C Language
Leave a Reply