Hacker News new | past | comments | ask | show | jobs | submit login

> "Correct in C90" means de facto correct, not that it was well-defined behavior. "Everyone" was doing it.

If "everyone" is defined as "people using GCC."




The use of an array of size [1] at the end of a structure is far broader than users of GCC. It is not a GCC extension; it's a trick which based on undefined behavior: accessing [2], [3], [4] ... in that array based on knowing that the space was malloced, which depends on the pointer arithmetic working, while the optimizer looks the other way.

C FAQ: [http://c-faq.com/struct/structhack.html]

"Despite its popularity, the technique is also somewhat notorious: Dennis Ritchie has called it ``unwarranted chumminess with the C implementation,'' and an official interpretation has deemed that it is not strictly conforming with the C Standard, although it does seem to work under all known implementations. (Compilers which check array bounds carefully might issue warnings.)"


I got the impression it was a GCC extension because it's listed in the "C Extensions" of the GCC documentation ( https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html ).

EDIT: the FAQ actually refers to arrays of one element where GCC makes a big deal about saving memory by accepting zero-length arrays. But you are correct that this kind of cleverness wasn't limited to GCC ( https://blogs.msdn.microsoft.com/oldnewthing/20031212-00/?p=... , https://blogs.msdn.microsoft.com/oldnewthing/20040826-00/?p=... ).


Three different ways to declare an array at the end of a structure:

[1] is the old school approach, which is still honored by compilers despite indexing past the first element technically being undefined behavior.

[0] is a GCC extension.

[] is C99.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: