Is the “struct hack” technically undefined behavior?

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

    If a compiler accepts something like

    typedef struct {
      int len;
      char dat[];
    };

    I think it's pretty clear that it must be ready to accept a subscript on 'dat' beyond its length. On the other hand, if someone codes something like:

    typedef struct {
      int whatever;
      char dat[1];
    } MY_STRUCT;

    and then later accesses somestruct->dat[x]; I would not think the compiler is under any obligation to use address-computation code which will work with large values of x. I think if one wanted to be really safe, the proper paradigm would be more like:

    #define LARGEST_DAT_SIZE 0xF000
    typedef struct {
      int whatever;
      char dat[LARGEST_DAT_SIZE];
    } MY_STRUCT;

    and then do a malloc of (sizeof(MYSTRUCT)-LARGEST_DAT_SIZE + desired_array_length) bytes (bearing in mind that if desired_array_length is larger than LARGEST_DAT_SIZE, the results may be undefined).

    Incidentally, I think the decision to forbid zero-length arrays was an unfortunate one (some older dialects like Turbo C support it) since a zero-length array could be regarded as a sign that the compiler must generate code that will work with larger indices.

提交回复
热议问题