What is the advantage of zero filling in calloc() ?

Showing Answers 1 - 6 of 6 Answers

ravi_529

  • Jan 22nd, 2008
 

most of the times you need to zero out the mem by using bzero or memset.U need not do it that way here.And also if it is to be alocated for a string,strlen(allocated array) is automatically 0.Which is a much safer method.

  Was this answer useful?  Yes

kbjarnason

  • Jul 1st, 2010
 

I rarely use calloc; the zero-filling is, for the most part, simply a waste of cycles.  In general, you know how much data in stuffed in your buffer, so just read that much back out.

However, there may be cases where it is useful, particularly if the buffer will be randomly filled.  As a trivial example, allocate a buffer with 52 elements representing A-Z and a-z.  Read characters from a file, updating the buffer; if you read an 'f', write 'f' into the appropriate element.  At the end, any elements which are still 0 represent characters which weren't in the file (Q, perhaps?).

The same effect can be achieved with a malloc and a memset.   Presumably, somewhere, there is (or was) a popular system where the OS or hardware would provide an efficiently zero-filled buffer if asked to, hence the function.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions