by stevenhuang · 7y ago · 0 comments
So if you do
void func(int x[10]);
You're free to call it like int k[5];
func(k);
And you won't get any warnings. Unsettling! void func(int x[static 10]);
must be called with an argument that is a pointer to the start of a big enough array of int. I can't get recent GCC or Clang to warn on violations of this, though. void foo(int *p)
{
func(p);
}
How can the compiler know if `p` points to space for 10 integers?The C FAQ is pretty old though, I’ve always wondered how much of that advice changed in C99/C11... from cursory googling things don’t seem to have changed much.
struct foo { char a[5]; };
void f(struct foo x) { x.a[4] = '\0'; printf("%s", x.a); }
int main(void) {
struct foo x;
memcpy(x.a, "too big", sizeof(x.a));
f(x)
printf("%s", x.a); /* read past end of x, crash */
return 0;
}
I'm thankful they didn't make structs decay into pointers!