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

寵の児 提交于 2021-02-07 14:12:39

问题


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

回答1:


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




回答2:


C11 documentation has this explicit notice for calloc

Footnotes

296) Note that this need not be the same as the representation of floating-point zero or a null pointer constant.

In practice, all zero bits is a (or the) representation for 0.0 and null pointer on major platforms and true for IEEE 754.




回答3:


C standard deliberately avoids specifying the way that float and double are represented:

6.2.6.1 General

  1. The representations of all types are unspecified except as stated in this subclause.

Therefore, you have no guarantee that calloc would produce 0.0 values.

Representation of unsigned integers, on the other hand, is specified as follows:

If there are N value bits, each bit shall represent a different power of 2 between 1 and 2N−1, so that objects of that type shall be capable of representing values from 0 to 2N − 1 using a pure binary representation.

Therefore, the value of calloc-ed unsugned int is guaranteed to be zero.




回答4:


All bytes zero for a float does not mean 0.0. From here

Initialization to all bits zero does not guarantee that a floating-point or a pointer would be initialized to 0.0 and the null pointer value, respectively (although that is true on all common platforms)



来源:https://stackoverflow.com/questions/53783149/does-calloc-of-a-double-field-always-evaluate-to-0-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!