3 ms·
It's funny that K&R chose to have arrays "decay" to pointers, but to allow structs to be passed by value. Thus you can actually pass arrays by value if and onl
by cryptonector 7y ago
It's funny that K&R chose to have arrays "decay" to pointers, but to allow structs to be passed by value. Thus you can actually pass arrays by value if and only if you wrap them in a struct:
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!
- jandrese 7y agoI figured that having arrays decay into pointers is one of those features that got grandfathered in because changing it would have broken the dozen or C programs that existed at the time. It's a real shame too because a working sizeof() for strings could have avoided a LOT of C exploits over the years.