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 valuesMemory is set to zero
Slightly fasterSlightly 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
C Pointers
C Pointer Arithmetic
C Pointer to Pointer
C Pointers and Arrays
C Pointers and Functions
C Dynamic Memory Allocation
Exercises & Assignments
No Content Found.
Interview Questions & Answers
What is a pointer in C?
What is a NULL pointer in C?
What is the difference between malloc() and calloc() in C?
What is a memory leak in C and how to avoid it?
What is a dangling pointer in C?
What is the difference between an array and a pointer in C?
What is a void pointer in C?