The following code compiles and runs, but shouldn't, because the size of structure a overflows size_t type. Overflowed size is checked for arrays, for global and local variables, but not for structures. struct a { char x[0x7fffffff]; char b[0x7fffffff]; char c[3]; }; main() { struct a *b = malloc(sizeof(struct a)); return sizeof (struct a); }
On the mainline we warn: t68.c:9: warning: integer overflow in expression So maybe this can be considered fixed.
Subject: Re: Gcc doesn't check overflowed size of structure If you rewrite it to int main(void) { size_t c = sizeof(struct a); struct a *b = malloc(c); return sizeof (struct a); } , it doesn't give warning with -W -Wall (except for unused b). BTW. for array too large it gives error, so I think for structure, it should too. Mikulas
Note if you make a global variable of the struct we do error out.
Confirmed.
(In reply to comment #2) > Subject: Re: Gcc doesn't check overflowed size of structure > > If you rewrite it to That is because there is no constant overflow. Just an overflow at the runtime.
(In reply to comment #5) > (In reply to comment #2) > > Subject: Re: Gcc doesn't check overflowed size of structure > > > > If you rewrite it to > > That is because there is no constant overflow. Just an overflow at the > runtime. > So, is this bug invalid? If not, what is the expect output?
Reconfirmed with today's trunk (7.0), 6.1.0, and all prior supported versions. It seems that it shouldn't be too hard to diagnose either the definition of the struct or the sizeof expression. $ cat uu.c && /build/gcc-trunk-svn/gcc/xgcc -B /build/gcc-trunk-svn/gcc -Wall -Wextra -Wpedantic -m32 uu.c && ./a.out struct a { char x[0x7fffffff]; char b[0x7fffffff]; char c[3]; }; int main() { __builtin_printf ("%zu\n", sizeof (struct a)); _Static_assert (sizeof (struct a) > sizeof ((struct a*)0)->x, ""); } uu.c: In function ‘main’: uu.c:10:37: warning: expression in static assertion is not an integer constant expression [-Wpedantic] _Static_assert (sizeof (struct a) > sizeof ((struct a*)0)->x, ""); ~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~ uu.c:10:3: error: static assertion failed: "" _Static_assert (sizeof (struct a) > sizeof ((struct a*)0)->x, ""); ^~~~~~~~~~~~~~
I think we should diagnose the definition of the struct (generally, any construction of a too-large fixed-size type in any context).