Search code examples
cfloating-pointintdoublecalloc

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);

Solution

  • 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).