Is the “struct hack” technically undefined behavior?

前端 未结 8 1520
误落风尘
误落风尘 2020-11-22 13:13

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         


        
8条回答
  •  粉色の甜心
    2020-11-22 13:39

    As the C FAQ says:

    It's not clear if it's legal or portable, but it is rather popular.

    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.)

    The rationale behind the 'strictly conforming' bit is in the spec, section J.2 Undefined behavior, which includes in the list of undefined behavior:

    • An array subscript is out of range, even if an object is apparently accessible with the given subscript (as in the lvalue expression a[1][7] given the declaration int a[4][5]) (6.5.6).

    Paragraph 8 of Section 6.5.6 Additive operators has another mention that access beyond defined array bounds is undefined:

    If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

提交回复
热议问题