Search code examples
cpointersdynamic-memory-allocation

When should i use calloc over malloc


This is from Beej's guide to C "The drawback to using calloc() is that it takes time to clear memory, and in most cases, you don't need it clear since you'll just be writing over it anyway. But if you ever find yourself malloc()ing a block and then setting the memory to zero right after, you can use calloc() to do that in one call."

so what is a potential scenario when i will want to clear memory to zero.


Solution

  • When the function you are passing a buffer to states in its documentation that a buffer must be zero-filled. You may also always zero out the memory for safety; it doesn't actually take that much time unless the buffers are really huge. Memory allocation itself is the potentially expensive part of the operation.