Difference Between malloc() and calloc() with Examples
Pre-requisite: Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
The functions malloc() and calloc() are library functions that allocate memory dynamically. Dynamic means the memory is allocated during runtime (execution of the program) from the heap segment.
malloc() allocates a memory block of given size (in bytes) and returns a pointer to the beginning of the block. malloc() doesn’t initialize the allocated memory. If you try to read from the allocated memory without first initializing it, then you will invoke undefined behavior, which will usually mean the values you read will be garbage.
calloc() allocates the memory and also initializes every byte in the allocated memory to 0. If you try to read the value of the allocated memory without initializing it, you’ll get 0 as it has already been initialized to 0 by calloc().
malloc() takes a single argument, which is the number of bytes to allocate.
Unlike malloc(), calloc() takes two arguments:
1) Number of blocks to be allocated.
2) Size of each block in bytes.
After successful allocation in malloc() and calloc(), a pointer to the block of memory is returned otherwise NULL is returned which indicates failure.
Values of allocated_with_calloc: 0 0 0 0 0 The allocation failed, the value of failed_malloc is: (nil)
Let us see the differences in a tabular form -:
|1.||It is a function that creates one block of memory of a fixed size.||It is a function that assigns more than one block of memory to a single variable.|
|2.||It only takes one argumemt||It takes two arguments.|
|3.||It is faster than calloc.||It is slower than malloc()|
|4.||It has high time efficiency||It has low time efficiency|
|5.||It is used to indicate memory allocation||It is used to indicate contiguous memory allcoation|