Difference between malloc() and calloc()?

1. Introduction

In C programming, the malloc() and calloc() are two functions used for dynamic memory allocation. They both allocate memory from the heap at runtime, but they have different behaviors and characteristics.

2. Key Points

1. malloc() stands for memory allocation and is used to allocate a single block of memory.

2. calloc() stands for contiguous allocation and is used to allocate multiple blocks of memory.

3. malloc() does not initialize the memory it allocates, while calloc() initializes the allocated memory to zero.

4. The way memory size is specified differs between malloc() and calloc().

3. Differences

malloc() calloc()
Allocates memory blocks in one contiguous block. Allocates memory in multiple contiguous blocks.
Does not initialize the allocated memory (contains garbage values). Initializes all bytes in the allocated memory to zero.
Syntax: malloc(size) Syntax: calloc(num, size)

4. Example

// Example using malloc()
int* ptr;
int n = 5;
ptr = (int*)malloc(n * sizeof(int));

// Example using calloc()
int* ptr;
int n = 5;
ptr = (int*)calloc(n, sizeof(int));

Output:

// Both examples do not produce a direct output as they are related to memory allocation.

Explanation:

1. In the malloc() example, memory for 5 integers is allocated without initialization.

2. In the calloc() example, memory for 5 integers is allocated and each integer is initialized to 0.

5. When to use?

- Use malloc() when you need a block of memory without initialization, or when memory initialization is not a concern.

- Use calloc() when you need multiple blocks of memory that you want to initialize to zero, often used for arrays or structures.

Difference between malloc() and calloc()?

Difference between Local Variable and Global Variable in C

Difference between Global and Static Variables in C

Difference Between Call by Value and Call by Reference in C

Difference Between getch() and getche() in C

Difference between printf() and sprintf() in C

Difference between Arrays and Pointers in C

Difference between Structure and Union in C

Difference Between Stack and Heap Memory Allocation in C

Difference Between Macro and Function in C

Difference between = and == in C

Difference Between for loop and while loop in C

Difference Between Linked List and Array in C

Difference between fgets() and gets() in C

Difference between ++i and i++ in C

Difference between struct and typedef struct in C

Difference between int main() and void main() in C

Difference between Character Array and String in C

Difference between break and continue in C

Difference between exit() and return in C

Comments