October 24, 2024
Chicago 12, Melborne City, USA
C#

Treat array as if it were a flexible array member? Undefined behavior?


Ideally, I want to have something like this:

struct S {
  // ...
  union {
    void *ptr;
    char buf[];
  };
};

That is, a struct with either a pointer to external storage, or intrusive storage of data. But standard C doesn’t allow unions to have flexible array members. (My reading of the standard is that it doesn’t explicitly forbid it, but adds flexible array members as a special case only for structures.)

But what if I did this instead:

struct S {
  // ...
  union {
    void *ptr;
    char buf[ sizeof(void*) ];
  };
};

When I want to use intrusive storage, I would do this:

if ( buf_size < sizeof(void*) )  // just in case
  buf_size = sizeof(void*);
struct S *s = malloc( sizeof(struct S) - sizeof(void*) + buf_size );

then read/write data to s->buf of some object of type T where sizeof(T)sizeof(void*).

Is that OK? Or undefined behavior?

(I believe before flexible array members were added to C, declaring buf[1] and just malloc‘ing a bigger size were common practice.)



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video