Eric Sosman
8/19/2011 12:02:00 PM
On 8/19/2011 6:28 AM, Hallvard B Furuseth wrote:
> I seem to remember the "struct hack" is safer if the fake
> dynamic array has character type. If that's right, where/why?
> Maybe in C99, since the struct hack is undefined in C89? Or
> real life implementations, nothing to do with the standard?
>
> That is,
> typedef<char or int> T;
> struct hack { Foo foo; T dynamic[1]; };
> struct hack h = malloc(sizeof *h) + sizeof(T)*n;
Garbled syntax? ITYM
struct hack *h = malloc(sizeof *h + sizeof(T)*n);
> .... use h->dynamic[0..n-1] ...;
Aside: Since sizeof(*h) already includes storage for one
T element, you could use h->dynamic[0..n] (or use n-1 in the
malloc).
> would be safer with T = char than with T = int.
>
> The C FAQ does not mention it. And I know about C99
> flexible array members, but that's not the question.
I can't see any reason to think a trailing char[] is any
more or less risky than a trailing T[]. Both will (almost
always) work, and neither is guaranteed to work.
Perhaps the relative riskiness involved a slightly
different situation, something like
typedef<char or whatever> T;
struct hack { int this; double that; }; // no T[]
#define PAYLOAD(hackptr) (T*)((hackptr) + 1)
h = malloc(sizeof *h + sizeof(T)*n);
... use PAYLOAD(h)[0..n-1]
This form certainly *is* safer with char T, because you don't
have alignment issues with the payload. (In fact, this form
is perfectly well-defined if the alignment issues are avoided
or dealt with -- but dealing with them is clumsy, hence there's
a temptation not to do so and incur the risk.)
--
Eric Sosman
esosman@ieee-dot-org.invalid