-
calloc vs malloc
Hey guys, quick question.
What exactly is the difference(benefit) of using calloc over malloc
They seem dreadfully similar to me.
int *p;
int *q;
p = (int *)calloc(5,sizeof(int)); // allocates 5 ints
q = (int *)malloc(5 * sizeof(int)); // allocates 5 ints gasp
So, what's the idea behind having the two different memory allocation functions?
-
>What exactly is the difference
Supposedly calloc is there to improve the syntax of malloc so that it's easier to understand. They both finish with the same result but each gets there in a different way, malloc takes the complete size for a block of memory to allocate as an argument and calloc takes the number of elements and the size of each element as arguments.
calloc will do the calculation for the size of the entire block to allocate insude the function while malloc doesn't need to. This probably saves an instruction or two, but is really not that important. Most people will use malloc because it is the most common.
Another difference is in how the allocated memory is initialized. malloc does nothing to initialize the memory it allocates but calloc will attempt to initialize the memory to all bits zero if possible.
-Prelude
-