I know that calloc allocates memory and writes zeroes to each cell, so my question is: is there a difference between using calloc or using malloc and running over the cells writing NULL to them? Are the zeroes of calloc equivalent to NULL?
Asked
Active
Viewed 5,075 times
5
-
`NULL` might not `0`(all bits are 0) as a representation. – BLUEPIXY Apr 22 '15 at 14:26
-
Some interesting issues with implementation here - http://locklessinc.com/articles/calloc/ – Brian Agnew Apr 22 '15 at 14:28
-
@BrianAgnew Why doesn't OP in the article simply check for overflow with: `n > SIZE_MAX/size` – 2501 Apr 22 '15 at 14:42
-
@2501 - I don't know. Perhaps they're simply being concise for the purposes of the article – Brian Agnew Apr 22 '15 at 14:49
-
What "cells"? The memory allocated `malloc` and `calloc` can be used to store objects of any type. Are you assuming the allocated space will be used to store pointer values? – Keith Thompson Apr 22 '15 at 15:27
2 Answers
5
No, they are not always equivalent, but on most popular machines you'll be fine. calloc
writes a bit pattern of all-zeros to the allocated memory, but the null pointer value might not be all-bits-zero on some machines (or even just for some types on some machines).
Check out the Null Pointers section of the C FAQ for lots and lots of information.

Carl Norum
- 219,201
- 40
- 422
- 469
-
Updated URL for the Null Pointers section: http://c-faq.com/null/index.html – cooltea Jan 13 '22 at 20:38
-
1
2
NULL isn't guaranteed to have all bits set to 0, even thought it always compares equal to the integer constant 0.
Calloc will set all of the bits to 0 the same as a memset call would. It is permitted that the resulting value(s) will not compare equal to NULL.
Therefore they are not equivalent.

2501
- 25,460
- 4
- 47
- 87