BCA / B.Tech 8 min read

malloc() & calloc() in C

malloc() & calloc() in the C Language:


In the C programming language, an important part of memory management is dynamic memory allocation, where memory is allocated at runtime. In C, two main functions are used for dynamic memory allocation: `malloc()` and `calloc()`. These functions help programmers to manually allocate and manage memory.

Introduction to malloc() and calloc():
1. malloc() (Memory Allocation): The `malloc()` function is used to dynamically allocate a single large block of memory. It allocates memory based on the number of bytes given. The allocated memory is uninitialized.
2. calloc() (Contiguous Allocation): The `calloc()` function also allocates dynamic memory, but it allocates multiple blocks of memory and initializes the allocated memory to 0.

The document provides syntax, examples, features, and drawbacks for both `malloc()` and `calloc()`. It also highlights the main differences between them and explains the necessity of using the `free()` function to deallocate memory after use.

Advantages and Disadvantages:
Advantages: Dynamic memory allocation, flexibility, and suitability for large programs and data structures.
Disadvantages: Risk of memory leaks, potential for NULL pointers if allocation fails, and the need for initialization with `malloc()`.