Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why calloc takes two arguments while malloc only one?

Tags:

c

calloc

IMO one is enough, why does calloc require to split it into two arguments?

like image 329
x86 Avatar asked Sep 24 '11 01:09

x86


People also ask

Why does calloc have 2 arguments?

The calloc() function takes two arguments: the number of elements to allocate and the storage size of those elements. Typically, calloc() implementations multiply these arguments to determine how much memory to allocate.

Why is calloc different than malloc?

malloc() and calloc() functions are used for dynamic memory allocation in the C programming language. The main difference between the malloc() and calloc() is that calloc() always requires two arguments and malloc() requires only one.

Why is realloc () needed when calloc () and malloc () is already available?

“realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a previously allocated memory. In other words, if the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory.

How many arguments malloc () takes?

malloc() takes a single argument (the amount of memory to allocate in bytes), while calloc() takes two arguments — the number of elements and the size of each element. malloc() only allocates memory, while calloc() allocates and sets the bytes in the allocated region to zero.


2 Answers

I'd guess that this is probably history and predates the times where C had prototypes for functions. At these times without a prototype the arguments basically had to be int, the typedef size_t probably wasn't even yet invented. But then INTMAX is the largest chunk you could allocate with malloc and splitting it up in two just gives you more flexibility and allows you to allocate really large arrays. Even at that times there were methods to obtain large pages from the system that where zeroed out by default, so efficiency was not so much a problem with calloc than for malloc.

Nowadays, with size_t and the function prototype at hand, this is just a daily reminder of the rich history of C.

like image 165
Jens Gustedt Avatar answered Oct 08 '22 03:10

Jens Gustedt


The parameter names document it reasonably well:

void *malloc(size_t size);
void *calloc(size_t nelem, size_t elsize);

The latter form allows for neat allocating of arrays, by providing the number of elements and element size. The same behavior can be achieved with malloc, by multiplying.

However, calloc also initializes the allocated memory to 0. malloc does no init, so the value is undefined. malloc can be faster, in theory, due to not setting all the memory; this is only likely to be noted with large amounts.

In this question, it is suggested that calloc is clear-alloc and malloc is mem-alloc.

like image 25
ssube Avatar answered Oct 08 '22 01:10

ssube