It would be great if GCC warned on this: extern int func_(char x[32]); int main(int argc, char *argv[]) { char p[8]; return func(p); } Failing that, if __builtin_object_size() returned a compile-time constant where possible, we could do this (with __builtin_constant_p): #define SIZE_CHECK(v,min) ({static_assert(__builtin_object_size((v), 0) >= (min), "too small"); (v)}) extern int func_(char x[32]); #define func(x) func_(SIZE_CHECK((x),32))
In C99 you can add "static" to the array function argument: extern int func(char x[static 32]); But unfortunately gcc doesn't warn for this case yet. Clang already does: markus@x4 /tmp % clang -c test.i test.i:5:10: warning: array argument is too small; contains 8 elements, callee requires at least 32 [-Warray-bounds] return func(p); ^ ~ test.i:1:22: note: callee declares array parameter as static here extern int func(char x[static 32]); ^~~~~~~~~~~~ 1 warning generated.
See also bug 45840 for a (somewhat remotely) related request involving pointers to arrays. I also think that warning on the test case in comment #1 would be a useful enhancement. Not having tested it, though, I would worry that issuing a warning on the test case in comment #0 by default (or with -Wall) would cause too many false positives. I suppose it could be something to try.
(In reply to Markus Trippelsdorf from comment #1) > In C99 you can add "static" to the array function argument: > > extern int func(char x[static 32]); > > But unfortunately gcc doesn't warn for this case yet. Bug 50584 that tracks this feature request.
GCC 11 reports the following warning (with or without static): $ gcc -S pr67793.c pr67793.c: In function ‘main’: pr67793.c:6:16: warning: ‘func’ accessing 32 bytes in a region of size 8 [-Wstringop-overflow=] 6 | return func(p); | ^~~~~~~ pr67793.c:6:16: note: referencing argument 1 of type ‘char *’