C Lesson 21 – malloc and calloc | Dataplexa

malloc() vs calloc() in C

In the previous lesson, you learned how to allocate memory dynamically.

Now, it is time to clearly understand the difference between malloc() and calloc().

Many beginners memorize this difference. Good programmers understand it.


What Both Functions Do

Both malloc() and calloc():

  • Allocate memory from heap
  • Return a pointer to the allocated block
  • Require free() after use

But the way they allocate memory is different.


malloc() – Raw Memory Allocation

malloc allocates memory as a single block.


int *ptr = (int*) malloc(5 * sizeof(int));

Important points:

  • Memory contains garbage values
  • No automatic initialization
  • Slightly faster than calloc

You must manually assign values before using the memory.


calloc() – Clean Memory Allocation

calloc allocates memory for multiple elements and initializes them.


int *ptr = (int*) calloc(5, sizeof(int));

Key behavior:

  • All allocated memory is set to zero
  • Safer for beginners
  • Slightly slower due to initialization

Side-by-Side Understanding (Conceptual)

Think of memory like notebooks:

  • malloc → You get used pages with random scribbles
  • calloc → You get fresh blank pages

Both notebooks work — the difference is cleanliness.


Example: malloc() Behavior


#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr = (int*) malloc(3 * sizeof(int));

    printf("%d %d %d\n", arr[0], arr[1], arr[2]);

    free(arr);
    return 0;
}

Output will be unpredictable (garbage values).


Example: calloc() Behavior


#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr = (int*) calloc(3, sizeof(int));

    printf("%d %d %d\n", arr[0], arr[1], arr[2]);

    free(arr);
    return 0;
}

Output will be:

0 0 0


Performance Consideration

malloc is faster because:

  • No initialization step

calloc is safer because:

  • No accidental use of garbage data

Professional programmers choose based on use-case.


When to Use Which?

  • Use malloc when performance matters and you initialize manually
  • Use calloc when safety and clarity matter

Mini Practice

  • Allocate memory for 4 integers using malloc
  • Assign values and print them
  • Repeat using calloc
  • Observe differences

Quick Quiz

Q1. Which function initializes memory to zero?

calloc()

Q2. Which function is slightly faster?

malloc()

Q3. Do both require free()?

Yes

Q4. Is calloc safer for beginners?

Yes

Q5. Can malloc return zero-initialized memory?

No