Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calloc() and NULL

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?

like image 374
yoniyes Avatar asked Apr 22 '15 14:04

yoniyes


2 Answers

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.

like image 197
Carl Norum Avatar answered Sep 21 '22 14:09

Carl Norum


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.

like image 39
2501 Avatar answered Sep 24 '22 14:09

2501