C standard regarding sizeof overflowing size_t

感情迁移 提交于 2019-11-30 19:28:47

The C standard does not explicitly state that the size_t type is sufficient for working with the sizes of all objects or types, especially for hypothetical types that are not actually instantiated.

In C 2018 7.19 2, the standard says that size_t “is the unsigned integer type of the result of the sizeof operator”. That tells us about the type size_t but not about the values that may arise during computation. In 5.2.4, the standard recognizes that C implementations necessarily have limits, and that they must break down at various points.

7.19 4 says “The types used for size_t and ptrdiff_t should not have an integer conversion rank greater than that of signed long int unless the implementation supports objects large enough to make this necessary.” This reaffirms our desire that size_t be capable of representing the sizes of all supported objects, particularly since it implies that the existence of an object makes it “necessary” that size_t be able to represent it, but it is not an explicit statement that size_t must do so, nor does it apply to hypothetical types that can be described but not instantiated as objects.

Were we to evaluate n * sizeof(double), we know the result: 6.2.5 9 says “A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.” However, with sizeof(double[n]), it is not completely clear this applies because, although n is unsigned, it is not the direct operand of sizeof, where the computation of a result that cannot be represented occurs. The standard does not explicitly tell us that the result of this sizeof will be reduced in the same way.

Thus, this operation is not covered by the C standard.

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