ISO/IEC JTC1/SC22/WG14 N583 Proposal UK014a - Ensure size_t and ptrdiff_t are always valid ============================================================== NOTE - This proposal is an alternative to UK013a. BSI prefer the latter alternative, but are submitting both. Summary ------- This proposal modifies the rules for declarations so that size_t and ptrdiff_t values cannot overflow when generated in a strictly conforming manner. The proposal is in three parts, each of which is independent of the others. Conformance ----------- A C89 conforming program may be affected by this proposal, and cause a diagnostic to be generated, if it declares an overly large object. A strictly conforming program could be affected on a perverse implementation (for example, one that makes size_t be unsigned char). Discussion ---------- A C89 implementation can currently make the type size_t so small that it cannot hold all the values that can be generated by the sizeof operator or the offsetof macro, and similarly the type ptrdiff_t can be so small that it cannot hold the number of elements of a declared array and thus the result of a pointer subtraction. This problem can be solved either by requiring objects to be small enough that the relevant cases do not overflow (see proposal UK013a), or by generating a diagnostic when the overflow actually happens. The latter is viewed as preferable by some people, but is not possible in the case of pointer subtraction (where the result is determined at run time and not compile time). Thus the first two parts of the proposal restrict operators, while the third restricts declarations. The second part of the proposal is unsatisfactory, because it places a constraint in one subclause (6.4) applying to a pseudo-operator in another (7.1.6). However, Constraints cannot appear in the latter. Detailed proposal ----------------- [The three parts are independent of one another.] Part 1 ------ Add a new Constraint to subclause 6.3.3.4: The sizeof operator shall not be applied to an expression or to the name of a type such that the result is greater than the maximum value of an object of type size_t. Part 2 ------ Add a new Constraint to subclause 6.4: A constant expression shall not be derived from an expansion of the offsetof macro where the offset of the structure member (in bytes) is greater than the maximum value of an object of type size_t. Part 3 ------ Replace the Constraint of subclause 6.5.4.2 with: The expression delimited by [ and ] (which specifies the size of an array) shall be an integral constant expression that has a value greater than zero and less than or equal to the minimum of the absolute values of the minimum and maximum values of an object of type ptrdiff_t.