Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
710 views
in Technique[技术] by (71.8m points)

language lawyer - C standard regarding sizeof overflowing size_t

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]);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...