BCA / B.Tech 9 min read

calloc() & malloc() in C++

malloc() & calloc() in C++:


In the C programming language, memory management is a crucial part. When we run a program, it needs memory according to its requirements. Usually, this memory is provided in the form of stack or static memory, but sometimes dynamic memory is required. For dynamic memory allocation, there are some important functions in C, such as `malloc()` and `calloc()`. These functions allocate memory at run-time.

Dynamic Memory Allocation:
Dynamic memory allocation is a process in which memory is allocated to a program at run-time. It is different from static memory allocation, where memory is allocated in a predetermined size on the stack.

malloc() (Memory Allocation):
`malloc()` dynamically allocates memory. When we use `malloc()`, it allocates memory as a block and returns a pointer to that block. This allocated memory is uninitialized.
Features: Dynamically allocates a block of memory, the allocated memory has no initial value, returns a `void*` pointer, and returns `NULL` on failure.

calloc() (Contiguous Allocation):
`calloc()` is also used for dynamic memory allocation, but it works a bit differently from `malloc()`. `calloc()` allocates memory for multiple blocks at once and initializes them to zero.
Features: Allocates multiple blocks of memory at once, initializes all allocated blocks to zero, also returns a `void*` pointer, and returns `NULL` on failure.