Suppose we have the source:
#include <stdint.h>
#include <stdio.h>
struct foo
{
char b ;
char a [ SIZE_MAX ] ;
} ;
int main ( void )
{
const size_t z = sizeof ( struct foo ) ;
printf("%zu\n", z);
return 0 ;
}
What behavior can be expected from the compiler with respect to sizeof (struct foo)
? There can be no object of type struct foo
, since it's size would be greater than SIZE_MAX
.
I do not find this case covered in the discussion of the sizeof
operator in the (draft) C17 Standard (N2176).
I am using a version of gcc (outdated) that claims to adhere to the C11 standard (and, AFAICT, it does). It fails to compile and reports that struct foo
is too big. That seems reasonable, but is such source guaranteed not to compile, given adherence to the standard? I would be interested in answers specific to particular standards.
$ gcc --version | head -1
gcc (Ubuntu 5.4.0-6ubuntu1~16.04.12) 5.4.0 20160609
$ gcc -c -Wall -o /dev/null oversize.c
oversize.c:6:10: error: sizeof array `a` is too large
char a [ SIZE_MAX ] ;
^
If sizeof ( struct foo )
were an arithmetic expression computing the hypothetical size of struct foo
by adding the sizes of its various members and padding, it would be governed by the rules for unsigned integer arithmetic, which would wrap results modulo SIZE_MAX
+1, per C 2024 6.2.5.
However, sizeof
is not specified to perform arithmetic as if with the +
operator. It seems more appropriate it is governed by this rule in C 2024 6.5.1:
If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), the behavior is undefined.
sizeof
is defined to produce the size of its operand. The size that struct foo
would have is not in the range of size_t
, which is the result type of sizeof
. Therefore, the behavior is undefined.
Exceptional conditions have been undefined throughout all the C standards, although the wording was a bit different in C 1990, referring to an “exception” occurring instead of an “exceptional condition.“