H
Hallvard B Furuseth
I know the struct hack is dubious because it exceeds the array bounds of
the named string in the struct:
struct hack { <whatever>; char string[1]; };
struct hack *x = malloc(sizeof(*x) + strlen(foo));
strcpy(x->string, foo);
However looking at C99 6.2.6.1p6 (Representations of types - General),
it also seems dubious because there may be padding bytes after string[]
in the struct and their contents become unspecified, no matter what the
program actually stores there. Is that right? I don't remember that at
all from the struct hack discussions I've seen here and in comp.std.c.
C99 6.2.6.1p6 (Representations of types, General):
When a value is stored in an object of structure or union type,
including in a member object, the bytes of the object representation
that correspond to any padding bytes take unspecified values.[42]
Footnote 42) Thus, for example, structure assignment may be
implemented element-at-a-time or via memcpy.
Maybe there's nothing similar in C89, at least I can't find it, though
there is footnote 122 to memcmp (at least in the C89 draft I have here):
122. The contents of ``holes'' used as padding for purposes of
alignment within structure objects are indeterminate, unless the
contents of the entire object have been set explicitly, as by the
calloc or memset function. Strings shorter than their allocated space
and unions may also cause problems in comparison.
the named string in the struct:
struct hack { <whatever>; char string[1]; };
struct hack *x = malloc(sizeof(*x) + strlen(foo));
strcpy(x->string, foo);
However looking at C99 6.2.6.1p6 (Representations of types - General),
it also seems dubious because there may be padding bytes after string[]
in the struct and their contents become unspecified, no matter what the
program actually stores there. Is that right? I don't remember that at
all from the struct hack discussions I've seen here and in comp.std.c.
C99 6.2.6.1p6 (Representations of types, General):
When a value is stored in an object of structure or union type,
including in a member object, the bytes of the object representation
that correspond to any padding bytes take unspecified values.[42]
Footnote 42) Thus, for example, structure assignment may be
implemented element-at-a-time or via memcpy.
Maybe there's nothing similar in C89, at least I can't find it, though
there is footnote 122 to memcmp (at least in the C89 draft I have here):
122. The contents of ``holes'' used as padding for purposes of
alignment within structure objects are indeterminate, unless the
contents of the entire object have been set explicitly, as by the
calloc or memset function. Strings shorter than their allocated space
and unions may also cause problems in comparison.