What is the difference between malloc() and calloc() in C?
| malloc() | calloc() |
|---|---|
malloc(size) takes one argument (total bytes) | calloc(n, size) takes two arguments |
| Memory has garbage values | Memory is set to zero |
| Slightly faster | Slightly slower because of the zeroing |
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *a = calloc(3, sizeof(int));
printf("%d %d %d\n", a[0], a[1], a[2]);
free(a);
return 0;
}
Output:
Output of the above program is
0 0 0
Both return NULL if the memory is not available, and both must be released with free(). See Dynamic Memory Allocation.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |