Is the "struct hack" technically undefined behavior?

c, c89, undefined-behavior

Solution

Yes, it is undefined behavior.

C Language Defect Report #051 gives a definitive answer to this question:

The idiom, while common, is not strictly conforming

http://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_051.html

In the C99 Rationale document the C Committee adds:

The validity of this construct has always been questionable. In the response to one Defect Report, the Committee decided that it was undefined behavior because the array p->items contains only one item, irrespective of whether the space exists.

Problem

What I am asking about is the well known "last member of a struct has variable length" trick. It goes something like this: ``` struct T { int len; char s[1]; }; struct T *p = malloc(sizeof(struct T) + 100); p->len = 100; strcpy(p->s, "hello world"); ``` Because of the way that the struct is laid out in memory, we are able to overlay the struct over a larger than necessary block and treat the last member as if it were larger than the `1 char` specified. So the question is: Is this technique technically undefined behavior?. I would expect that it is, but was curious what the standard says about this. PS: I am aware of the C99 approach to this, I would like the answers to stick specifically to the version of the trick as listed above.

Original source