Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> C Language

malloc vs calloc: Key Differences Explained with Practical Examples

What is Dynamic Memory Allocation?

Dynamic memory allocation lets a program request and release memory at run time. In C, the standard library provides four primary functions for this purpose – malloc(), calloc(), realloc(), and free() – all declared in stdlib.h.

malloc(): Allocate a Single Block of Memory

malloc() (short for "memory allocation") reserves a contiguous block of bytes and returns a pointer to the first byte. The contents of the newly allocated block are indeterminate, meaning they contain whatever bits happened to be at that location in memory.

Typical usage:

int *p = (int *)malloc(n * sizeof(int));
If the request fails, malloc() returns NULL.

calloc(): Allocate Multiple Zero‑Initialized Blocks

calloc() (short for "contiguous allocation") takes two arguments: the number of elements and the size of each element. It allocates memory for all elements and automatically sets every byte to zero, making it ideal for arrays or structures that need a clean starting state.

Typical usage:

int *p = (int *)calloc(n, sizeof(int));
Like malloc(), it returns NULL if the allocation fails.

When to Use Each Function

Syntax Overview

malloc()

void *malloc(size_t size);

calloc()

void *calloc(size_t num, size_t size);

Practical Code Examples

Example 1: Using malloc() to Store 15 Integers

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

int main(void) {
    int *ptr = malloc(15 * sizeof(*ptr));
    if (!ptr) {
        perror("malloc failed");
        return EXIT_FAILURE;
    }
    ptr[5] = 480; // 6th element (0‑based index)
    printf("Value of the 6th integer is %d\n", ptr[5]);
    free(ptr);
    return EXIT_SUCCESS;
}

Output: Value of the 6th integer is 480

Example 2: Using calloc() to Compute a Sum

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

int main(void) {
    int *ptr = calloc(10, sizeof(int));
    if (!ptr) {
        perror("calloc failed");
        return EXIT_FAILURE;
    }
    int sum = 0;
    for (int i = 0; i < 10; ++i) {
        ptr[i] = i;      // initialization is redundant but shown for clarity
        sum += ptr[i];
    }
    printf("Sum = %d\n", sum);
    free(ptr);
    return EXIT_SUCCESS;
}

Output: Sum = 45

Side‑by‑Side Comparison

malloc vs calloc: Key Differences Explained with Practical Examples

Featuremalloc()calloc()
Number of parameters1 (size)2 (count, size)
Memory state after allocationUninitialized (garbage)Zero‑initialized
Typical use caseSingle block, manual initializationArrays or structures needing a clean start
PerformanceFaster (no zeroing)Slower (zeroing overhead)
SafetyHigher risk of using garbage valuesLower risk due to automatic zeroing
Return value on failureNULLNULL
Standard headerstdlib.hstdlib.h

Takeaway

C Language

  1. C++ do‑while Loop: Syntax, Practical Examples, and Nested Loops
  2. Mastering C++ Pointers: Concepts, Examples & Practical Applications
  3. C++ Operator Overloading – A Practical Guide with Code Examples
  4. C++ Functions Explained with Practical Code Examples
  5. C# Hashtable Explained: Key-Value Storage, Operations, and Practical Examples
  6. Understanding Switch‑Case in C: Syntax, Examples, and Best Practices
  7. Dynamic Memory Allocation in C: Mastering malloc, calloc, realloc, and free
  8. While vs. Do‑While Loops: Clear Comparison with Practical Examples
  9. malloc vs calloc: Key Differences Explained with Practical Examples
  10. calloc() in C: Zero‑Initialized Memory Allocation and a Practical Example