Explore
ProGrad Programs
Placement Prep
TCS Codevita
Live Placement Training
Live Aptitude Training
Live Programming Training
Webinars
About Us

Edit
Reply




Edit

Malloc and Calloc in C

Published on 06 Mar 2020

malloc and calloc are library functions that allocate memory dynamically, which means that memory is allocated during the runtime (execution of the program) from heap segment. malloc stands for memory allocation while calloc stands for contiguous allocation.


1) Initialization: malloc() allocates a memory block of given size and returns a pointer to the beginning of the block. malloc() doesn’t initialize the allocated memory. If we try to access the content of memory block then we’ll get garbage values. While calloc() allocates the memory and also initializes the allocated memory block to zero. If we try to access the content of these blocks then we’ll get 0.


Syntax

void * calloc( size_t num, size_t size );
void * malloc( size_t size );


2) The number of arguments: calloc() takes two arguments, while malloc takes only one.

1) The number of blocks to be allocated.

2) Size of each block.


3) Return Value: After successful allocation in malloc() and calloc(), a pointer to the block of memory is returned otherwise the NULL value is returned which means allocation has failed.


4) malloc is faster than calloc. calloc takes little longer than malloc as it need an extra step of initializing the allocated memory by zero. However, in practice the difference in speed is very tiny and not recognizable.

If you have any feedback about this article and want to improve this, please write to enquiry@faceprep.in