Calloc and realloc functions
calloc() and realloc() are two other dynamic memory allocation functions in C, which complement malloc() and free().
calloc() function is used to allocate a block of memory in which each byte is initialized to zero. It takes two arguments: the number of elements to allocate and the size of each element. The total size of the memory block is calculated as the product of the two arguments.
Example of calloc():
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 5;
int *ptr = NULL;
ptr = (int*) calloc(n, sizeof(int));
if (ptr == NULL) {
printf("Error: memory not allocated\n");
exit(0);
}
// Print values in the memory block
for (int i = 0; i < n; i++) {
printf("%d ", *(ptr + i));
}
// Free memory
free(ptr);
return 0;
}
Output:
0 0 0 0 0
realloc() function is used to resize the previously allocated block of memory. It takes two arguments: a pointer to the previously allocated memory block and the new size to which the block should be resized.
Example of realloc():
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 5;
int *ptr = NULL;
ptr = (int*) malloc(n * sizeof(int));
if (ptr == NULL) {
printf("Error: memory not allocated\n");
exit(0);
}
// Assign values to the memory block
for (int i = 0; i < n; i++) {
*(ptr + i) = i;
}
// Print values in the memory block
for (int i = 0; i < n; i++) {
printf("%d ", *(ptr + i));
}
// Resize memory block to hold 10 elements
ptr = (int*) realloc(ptr, 10 * sizeof(int));
// Assign values to the new memory block
for (int i = n; i < 10; i++) {
*(ptr + i) = i;
}
printf("\n");
// Print values in the memory block
for (int i = 0; i < 10; i++) {
printf("%d ", *(ptr + i));
}
// Free memory
free(ptr);
return 0;
}
Output:
0 1 2 3 4
0 1 2 3 4 5 6 7 8 9