Search code examples
cmalloccalloc

Initializing to zero after malloc or calling calloc


I have a small confusion in using calloc over malloc. I remember somewhere I have read that calloc is slower than malloc because calloc performs initialization to zero after performing memory allocation.

In the project I am working, I see that after malloc they are assigning zero to all the values as shown below,

str* strptr = (str*)malloc(sizeof(str));
memset(strptr,0,sizeof(str));

Here str is a structure.

This is similar to

str* strptr =(str*)calloc(1,sizeof(str));

I want to know whether using malloc over calloc has any advantages and which method is preferred.


Solution

  • I want to know whether using malloc over calloc has any advantages

    The differences between them are just

    • calloc also takes object count as opposed to malloc which only takes byte count
    • calloc zeros memory; malloc leaves the memory uninitialized

    So no exceptional advantages except for the zeroing part.

    which method is preferred.

    Why not use malloc the way its used in the code base you're looking at? To avoid duplication of work and code; when an API already does that why reinvent the wheel? You could have seen code bases with a utility function that does just that: allocate and zero memory. This shows that the snippet will be used many times and hence they wrap it in a macro/function to call it from different places. However, why do it when calloc already does that?

    The best code is no code at all. Lesser code is better, and thus you should prefer calloc over malloc here. May be the optimizer would do the same thing underneath, but why take the chance? Apparently, the optimizer may not be that smart, which is the reason for this question: Why malloc+memset is slower than calloc?

    Also the calloc route requires lesser key strokes.