calloc and malloc

calloc and malloc are both functions in C used for dynamic memory allocation, but they have some key differences.

calloc

calloc stands for “contiguous allocation.” It allocates memory for an array of elements, initializes all bytes to zero, and returns a pointer to the allocated memory.

Syntax:

void *calloc(size_t num, size_t size);
  • Parameters:
    • num: Number of elements.
    • size: Size of each element.

malloc

malloc stands for “memory allocation.” It allocates a specified number of bytes of memory and returns a pointer to the allocated memory. However, it does not initialize the memory.

Syntax:

void *malloc(size_t size);
  • Parameter:
    • size: Number of bytes to allocate.

Key Differences

  1. Initialization:
    • calloc: Initializes the allocated memory to zero.
    • malloc: Does not initialize the allocated memory; it contains garbage values.
  2. Parameters:
    • calloc: Takes two parameters (number of elements and size of each element).
    • malloc: Takes one parameter (total number of bytes to allocate).
  3. Usage:
    • calloc is useful when you need an array of elements initialized to zero.
    • malloc is useful when you need a block of memory without initialization.

Example

Here’s an example to illustrate the difference:

// Using calloc
int *arr1 = (int *)calloc(5, sizeof(int)); // Allocates memory for 5 integers and initializes them to 0

// Using malloc
int *arr2 = (int *)malloc(5 * sizeof(int)); // Allocates memory for 5 integers, but they contain garbage values

Would you like to see more examples or have any specific questions about these functions?




Enjoy Reading This Article?

Here are some more articles you might like to read next:

  • Learning-based memory allocation for C++ server workloads summary
  • my question:
  • Binary search algorithm variant
  • Docker Rocksdb build
  • Difference between Dockerfile and Docker Compose