malloc() vs calloc(): Key Differences in C Memory Allocation

·

Introduction

Dynamic memory allocation in C involves functions like malloc() and calloc(). Both allocate memory during runtime, but they differ in initialization and usage…

malloc()

The malloc() function allocates memory but does not initialize it. The memory contains garbage values.

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

calloc()

The calloc() function allocates memory and initializes it to zero.

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

Key Differences

Aspect malloc() calloc()
Initialization Does not initialize memory Initializes memory to zero
Syntax malloc(size) calloc(num, size)

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *