News for hackers. Stuff that matters.
Re:Function overloading in C by kazinator on Monday July 27, 2015 @12:05PM (#9955980)
Why programmers don't always use calloc: good question.

Firstly, anyone who does mallocs a block, and then immediately does a memset(block, 0, size) on that block almost certainly should be using calloc. The Linux kernel has kzalloc for this purpose as an alternative to kmalloc and it's fairly widely used.

Sometimes it is inefficient to set something to zero, when that is not the true initial value (some or all of the zeros will be overwritten with the true initial value before the object is used). If you malloc some structure and then painstakingly initialize every member, then calloc is wasteful.

If you malloc some structure, and then forget to initialize some of the members, calloc will hide that bug by initializing them to all zero bits. This might not be the correct value. If the uninitialized parts of the structure aren't clobbered from zeros, you can get an accurate diagnostic about that from a tool like Valgrind. On the other hand, if you aren't using that tool, the behavior with zeros is more deterministic. E.g. if a pointer is not initialized, but overwritten with zeros, on most mainstream platforms that will be a null pointer whose dereferencing uses are detected. If you don't have such a tool available, having the uninitialized bits be all zero is arguably better.

Much of this reasoning mirrors reasoning about whether to initialize a local variable to zero, if its true initialization actually happens later.

Re:Function overloading in C by danieltillett on Monday July 27, 2015 @05:51PM (#9958258)
In my experience using malloc over calloc make it much harder to find subtle bugs that result from off by one under set errors (i.e. you malloc 100 bytes, only set 99, and then you later read 100 bytes). When you use malloc the 100th byte is filled with random garbage, while with calloc you get something consistent.

Finding bugs where you write 101 bytes are easy to find with tools like Valgrind, but finding bugs where you malloc and don’t initialise the data structure correctly are a real pain.

Re:Function overloading in C by nitrogen on Tuesday July 28, 2015 @01:02PM (#9962961)
Valgrind will tell you about reading that 100th uninitialized byte.