lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

Roberto Ierusalimschy wrote in
 |> "char data[0]" is not supported by the C standard, it's a GNU extension I
 |> believe.
 |> You can use 'offsetof' to determine the offset of a structure member, you
 |> can do something like
 |> struct STRING
 |> {
 |>   size_t length;
 |>   char data[1];
 |> struct STRING* build_string(size_t size, const char* data)
 |> {
 |>   struct STRING* p = (struct STRING*)malloc(offsetof(struct STRING, \
 |>   data) +
 |> size);
 |>   p->length = size;
 |>   memcpy(p->data, data, size);
 |>   return p;
 |"char data[0]" is not standard C, and "char data[]" is not standard C89.
 |Lua uses exactly the technique described here, with offsetof, to
 |allocate Udata, CClosure, and LClosure without wasting memory.

Hm, i hate reading ISO standard so the exact wording i do not
know, but the above makes me think you do enter undefined area by
storing more in .data than is allowed (likely depending on
C compiler flags and optimization too, i have not looked what Lua

To overcome this, for my code, i use macros like VFIELD_SIZE(X)
which is empty for defined __STDC_VERSION__ && __STDC_VERSION__
+0 >= 199901l, but otherwise is a bit more complicated to come up
with an "aligned multiple" of uz (more or less size_t).  I then
say "char cm_buf[VFIELD_SIZE(0)];" when alignment fits, or "char
am_name[VFIELD_SIZE(3)];" when there are other fields in the
"current alignment slot"  (it is (((X) == 0 ? sizeof(uz) : (X
< 0 ? sizeof(uz) - ABS(X) : (X))))).

|Der Kragenbaer,                The moon bear,
|der holt sich munter           he cheerfully and one by one
|einen nach dem anderen runter  wa.ks himself off
|(By Robert Gernhardt)