In C programming language, the malloc() and calloc() functions are used to dynamically allocate memory at run-time. Both functions are declared in the stdlib.h header file and are used to allocate memory on the heap. Here are some of the key differences between the malloc() and calloc() functions:
Function signature: The malloc() function takes a single argument, which is the size of the memory block to allocate, in bytes. The calloc() function takes two arguments: the number of elements to allocate, and the size of each element, in bytes.
void *malloc(size_t size);
void *calloc(size_t count, size_t size);
Initialization: The malloc() function does not initialize the memory block, while the calloc() function initializes the memory block to zero.
int *ptr1 = malloc(10 * sizeof(int)); // Uninitialized memory
int *ptr2 = calloc(10, sizeof(int)); // Memory initialized to zero
In this example, the malloc() function is used to allocate a block of memory for 10 integers, but the memory is uninitialized and contains garbage values. The calloc() function, on the other hand, is used to allocate a block of memory for 10 integers and initializes the memory to zero.
Return value: The malloc() function returns a pointer to the allocated memory block, while the calloc() function returns a pointer to the first element of the allocated memory block.
int *ptr1 = malloc(10 * sizeof(int)); // Returns a pointer to the memory block
int *ptr2 = calloc(10, sizeof(int)); // Returns a pointer to the first element
In this example, the ptr1 pointer points to the memory block allocated by the malloc() function, while the ptr2 pointer points to the first element of the memory block allocated by the calloc() function.
Memory reallocation: The realloc() function can be used to reallocate memory that was previously allocated using either malloc() or calloc(). The realloc() function takes two arguments: a pointer to the previously allocated memory block, and the new size of the memory block, in bytes.
int *ptr1 = malloc(10 * sizeof(int)); // Allocates memory for 10 integers
int *ptr2 = calloc(10, sizeof(int)); // Allocates memory for 10 integers
ptr1 = realloc(ptr1, 20 * sizeof(int)); // Resizes the memory block to 20 integers
ptr2 = realloc(ptr2, 20 * sizeof(int)); // Resizes the memory block to 20 integers
In this example, the realloc() function is used to resize the memory blocks allocated by both the malloc() and calloc() functions.
In summary, the malloc() and calloc() functions are used to dynamically allocate memory at run-time. The malloc() function allocates uninitialized memory, while the calloc() function initializes the memory to zero. The malloc() function returns a pointer to the memory block, while the calloc() function returns a pointer to the first element. Both functions can be used with the realloc() function to resize previously allocated memory blocks.