Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does calloc() of a double field always evaluate to 0.0?

  • Does calloc() of a double field always evaluate to 0.0?

Furthermore:

  • Does calloc() of a float field always evaluate to 0.0f?
  • Does calloc() of an int or unsigned int field always evaluate to 0?

That is, will the assert() below always succeed on all platforms?

double* d = calloc(1, sizeof(double));
assert(*d == 0.0);
free(d);
like image 868
st12 Avatar asked Dec 14 '18 16:12

st12


1 Answers

The calloc sets all bytes of the allocated memory to zero.

As it happens, that's also the valid IEEE754 (which is the most common format for floating point values on computers) representation for 0.0.

IIRC there's no part of the C specification that requires an implementation to use IEEE754, so to be picky it's not portable. In reality though, it is (and if you're ever going to work on a non-IEEE754 system then you should have gathered enough experience to already know this and how to solve such problems).

Also note that this also is valid for pointers. On all systems you're likely to come in contact with, a null pointer should be equal to 0. But there might be systems where it isn't, but if you work on such systems you should already know about it (and if you use NULL then it should not be a problem).

like image 95
Some programmer dude Avatar answered Sep 25 '22 15:09

Some programmer dude