Is the “struct hack” technically undefined behavior?

前端 未结 8 1697
误落风尘
误落风尘 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:48

    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.

提交回复
热议问题