Both allocate heap memory, but they differ in two ways. malloc(size) takes a single byte count and leaves the memory uninitialized, it contains whatever was there before, so reading it before writing yields garbage. calloc(count, size) takes the element count and element size separately, and zero-initializes the whole block. So calloc(n, sizeof(int)) gives you n ints all set to 0. calloc also internally guards against the count * size multiplication overflowing, if it would overflow size_t, calloc fails safely, whereas a hand-written malloc(count * size) could overflow and under-allocate. Use calloc when you need a clean zeroed buffer or when computing the size from untrusted counts.
C Programming · Interview question
What's the difference between malloc and calloc?
A strong answer
What a weak answer sounds like
You know the answer. Do you know what gets you dinged?
Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.
From the lesson
Dynamic Memory: malloc & free
Sizing memory at runtime with malloc/calloc/realloc, and the discipline of free that prevents leaks, double-frees, and use-after-free bugs.