关于sizeof溢出size_t的C标准 [英] C standard regarding sizeof overflowing size_t

查看:243
本文介绍了关于sizeof溢出size_t的C标准的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是未定义的行为吗?该标准的相关部分并没有多说.

Is this undefined behavior? The relevant parts of the standard don't say much.

size_t n = SIZE_MAX / sizeof(double) + 1;
size_t m = sizeof(double[n]);

推荐答案

C标准没有明确声明size_t类型足以处理所有对象或类型的大小,特别是对于那些不适合所有类型的假设类型的对象实际实例化.

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.

在C 2018 7.19 2中,标准说size_t是sizeof运算符结果的无符号整数类型".这告诉我们有关类型 size_t的信息,而不是有关在计算过程中可能出现的的信息.在5.2.4中,该标准认识到C实现一定有局限性,并且它们必须在各个方面崩溃.

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说:用于size_tptrdiff_t的类型的整数转换等级不应大于signed long int的整数转换等级,除非实现支持足够大的对象以使之必要."这重申了我们的愿望,即size_t能够表示所有受支持对象的大小,特别是因为它暗示着一个对象的存在使size_t能够表示它成为必要",但这并不是明确的声明size_t必须这样做,也不适用于可以描述但不能实例化为对象的假设类型.

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.

如果我们对n * sizeof(double)求值,我们就会知道结果:6.2.5 9说:涉及无符号操作数的计算永远不会溢出,因为无法用所得的无符号整数类型表示的结果将以比结果类型可以表示的最大值大1."但是,对于sizeof(double[n]),这还不是很清楚,因为尽管n是无符号的,但它不是sizeof的直接操作数,在这里无法计算结果.该标准未明确告知我们sizeof的结果将以相同的方式降低.

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.

因此,C标准不涵盖此操作.

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

这篇关于关于sizeof溢出size_t的C标准的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆