0

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.

5
  • 1
    Not an exact duplicate, but this may help: stackoverflow.com/questions/2688466/… Dec 8, 2014 at 9:22
  • 1
    I would say, generally, malloc would be better because you will not be referring to the contents of allocated memory before you put something there. A possible exception might be if you're using the zeroes as a check whether you have indeed filled that location yet.
    – TheBigH
    Dec 8, 2014 at 9:26
  • That's a memcpy (mem copy) not a memset, so they are copying some variable o to the struct, which may or may not set all the values to zero. Dec 8, 2014 at 9:31
  • @user3386109 : sorry my mistake its memset with zero
    – evk1206
    Dec 8, 2014 at 9:33
  • @TheBigH +1 when you don't need zeroing memory (which is mostly the case), then preferring malloc makes perfect sense.
    – legends2k
    Dec 8, 2014 at 9:45

1 Answer 1

3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.