calloc() versus malloc() in C

In C, both malloc() and calloc() are used for dynamic memory allocation, but they have important differences in initialization and usage. Understanding when to use each function is crucial for effective memory management.

Syntax

void *malloc(size_t size);
void *calloc(size_t number, size_t size);

malloc() Function

The malloc() function allocates a block of memory of the specified size in bytes. It does not initialize the allocated memory, leaving it with garbage values.

Parameters

  • size − Size of memory block to allocate in bytes

Example

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

int main() {
    int n = 4, i, *p, s = 0;
    p = (int*) malloc(n * sizeof(int));
    
    if(p == NULL) {
        printf("Error! Memory not allocated.<br>");
        exit(1);
    }
    
    printf("Enter %d elements: ", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &p[i]);
        s += p[i];
    }
    
    printf("Sum: %d<br>", s);
    free(p);
    return 0;
}
Enter 4 elements: 32 23 21 8
Sum: 84

calloc() Function

The calloc() function allocates memory for an array of elements and initializes all bytes to zero. It stands for "contiguous allocation".

Parameters

  • number − Number of elements to allocate
  • size − Size of each element in bytes

Example

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

int main() {
    int n = 4, i, *p, s = 0;
    p = (int*) calloc(n, sizeof(int));
    
    if(p == NULL) {
        printf("Error! Memory not allocated.<br>");
        exit(1);
    }
    
    printf("Initial values: ");
    for(i = 0; i < n; i++) {
        printf("%d ", p[i]);
    }
    
    printf("\nEnter %d elements: ", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &p[i]);
        s += p[i];
    }
    
    printf("Sum: %d<br>", s);
    free(p);
    return 0;
}
Initial values: 0 0 0 0 
Enter 4 elements: 2 24 35 12
Sum: 73

Comparison

Feature malloc() calloc()
Initialization Uninitialized (garbage values) Initialized to zero
Parameters Single parameter (total size) Two parameters (count, size)
Speed Faster (no initialization) Slower (zero initialization)
Memory Usage Same Same

Key Points

  • Use malloc() when you plan to initialize values immediately
  • Use calloc() when you need zero-initialized memory
  • Always check for NULL return value before using allocated memory
  • Always use free() to deallocate memory and prevent memory leaks

Conclusion

Both malloc() and calloc() serve dynamic memory allocation needs. Choose malloc() for faster allocation when initialization isn't needed, and calloc() when you need zero-initialized memory arrays.

Updated on: 2026-03-15T09:56:14+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements