Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]);
like image 982
ov2k Avatar asked Sep 03 '19 03:09

ov2k


1 Answers

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.

like image 107
Eric Postpischil Avatar answered Oct 04 '22 20:10

Eric Postpischil