lua-users home
lua-l archive

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


The safe option that does it waste extra padding bytes at end of the structure is to declare the last byte array with a size 0 and not one. The compiler will align the byte array if needed  it it should not do that, because byte arrays should be byte aligned and not word aligned except if this array has some prepaddng declared or if the array has specific declarators to force the alignment (including by de Mari g this array in an union with other types with alignment constraints)

Declaring the last member as char[1] is not the best choice. char[0] would be better.

Le mar. 12 mai 2020 à 18:28, Roberto Ierusalimschy <roberto@inf.puc-rio.br> a écrit :
>   typedef struct TString {
>     CommonHeader;
>     lu_byte extra;
>     lu_byte shrlen;
>     unsigned int hash;
>     union {
>       size_t lnglen;
>       struct TString *hnext;
>     } u;
>     char bytes[1];
>   } TString;
>
>   #define getstr(ts) check_exp(sizeof((ts)->extra), ts->bytes)
>
>   #define sizelstring(l)  (sizeof(TString) + (l) * sizeof(char))

This code wastes up to seven bytes (due to alignment), compared with
the original version. A better option would be to use 'offsetof' to
compute the size of the rest of the structure:

#define sizelstring(l)  (offsetof(TString, bytes) + ((l) + 1) * sizeof(char))

I hope the new gcc does not complain about that code.

-- Roberto
_______________________________________________
lua-l mailing list -- lua-l@lists.lua.org
To unsubscribe send an email to lua-l-leave@lists.lua.org
_______________________________________________
lua-l mailing list -- lua-l@lists.lua.org
To unsubscribe send an email to lua-l-leave@lists.lua.org