Difference Between malloc and calloc in C

Difference Between malloc and calloc in C

In C programming, dynamic memory allocation is a crucial aspect, and the functions malloc and calloc are commonly used for this purpose. While both functions allocate memory, they differ in several ways.

malloc (Memory Allocation)

The malloc function is used to allocate a single block of memory of a specified size. The allocated memory is not initialized, meaning it contains whatever data was previously at that memory location (i.e., garbage values).

Syntax:

void* malloc(size_t size);

Here, size is the number of bytes to allocate.

Example:

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

int main() {
    int *ptr;

    // Allocating memory for 5 integers
    ptr = (int*) malloc(5 * sizeof(int));

    if (ptr == NULL) {
        printf("Memory allocation failed\\n");
        return 1;
    }

    // Freeing the allocated memory
    free(ptr);

    return 0;
}

calloc (Contiguous Allocation)

The calloc function allocates memory for an array of elements and initializes all bytes to zero. This function is useful when you need to ensure that the allocated memory is initialized.

Syntax:

void* calloc(size_t num_elements, size_t element_size);

Here, num_elements is the number of elements to allocate, and element_size is the size of each element.

Example:

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

int main() {
    int *ptr;

    // Allocating memory for 5 integers
    ptr = (int*) calloc(5, sizeof(int));

    if (ptr == NULL) {
        printf("Memory allocation failed\\n");
        return 1;
    }

    // Freeing the allocated memory
    free(ptr);

    return 0;
}

Key Differences Between malloc and calloc

  • Initialization: malloc does not initialize the allocated memory, whereas calloc initializes the allocated memory to zero.
  • Parameters: malloc takes one argument: the total number of bytes to allocate. calloc takes two arguments: the number of elements and the size of each element.
  • Memory Allocation: malloc allocates a single block of memory. calloc allocates multiple blocks of memory, one for each element.
Note: Always check if the memory allocation was successful by checking if the pointer returned by malloc or calloc is NULL. If it is NULL, the memory allocation failed.

Comments

Popular Posts