Search code examples
cflexible-array-member

Struct with flexible array member and allocating memory for it


I was reading this version of the C99 standard linked by Wikipedia to try to understand how flexible array members work.

In section 6.7.2.1, this struct was declared:

struct s { int n; double d[]; };

And an example was given:

s1 = malloc(sizeof (struct s) + 10);
s2 = malloc(sizeof (struct s) + 6);

Where it said that s1 and s2 would behave as if the declarations were:

struct { int n; double d[1]; } *s1, *s2;

and it listed some things you can do:

double *dp;
dp = &(s1->d[0]); // valid
*dp = 42; // valid
dp = &(s2->d[0]); // valid
*dp = 42; // undefined behavior

I can see why the last line above is undefined since s2 was only allocated 6 extra bytes which is not enough to store a double, but then I don't understand why it would say that the behaviour of s1 and s2 would be like if they were declared as:

struct { int n; double d[1]; } *s1, *s2;

When it seems like s2 has not been allocated enough memory to store that struct.

The document seems to be some kind of draft so I'm not sure if there's been an error or if I'm misunderstanding what is meant.


Solution

  • (You shouldn't be looking into C99 anymore, it is obsolete. C11 is document n1570 at the same place that your are citing. It will probably/hopefully soon be replaced by C17.)

    The reason, I think, that it says it behaves as if it had one element is the phrase

    If it would have no elements, such an array behaves as if it had one element but the behavior is undefined if any attempt is made to access that element...