Abhishek Jaiswal
Abhishek Jaiswal

Reputation: 308

How is the memory allocation done by malloc and calloc function in C?

malloc() allocates a single block of memory whereas calloc() allocates multiple blocks of memory, each block with the same size.

How do they differ from each other in internal implementation?

I tried the below code and tried to figure out the difference between the internal implementation of malloc and calloc (considering the above-quoted text).

#include<stdio.h>
#include<stdlib.h>
int main()
{
   int *p=(int*)malloc(2*sizeof(int));
   p[0]=3;
   p[1]=4;
   printf("%d\t%d",p[0],p[1]);
   free(p);
   int *q=(int*)calloc(2,sizeof(int));
   q[0]=1;
   q[1]=2;
   printf("\n%d\t%d",q[0],q[1]);
   free(q);
   return 0;
}

But I didn't find any difference(from the output) between these two functions. What change should I do to understand the internal implementation of both functions? Here my meaning to the internal implementation is mentioned in the above-quoted text.

I hope you got my question.

Thanks

Upvotes: 0

Views: 300

Answers (1)

Sunil Bojanapally
Sunil Bojanapally

Reputation: 12658

There is no big difference with the internal implementation perspective of both, or on most implementations calloc does use malloc followed by memset to zero the memory allocated as shown below example snippet. Refer to calloc implementation.

void *calloc(size_t n, size_t elem_size)
{
    const size_t nbytes = n * elem_size;
    void *p = malloc(nbytes);
    if (p != NULL) {
       memset(p, 0, nbytes);
    }
    return p;
}

Upvotes: 3

Related Questions