lua-users home
lua-l archive

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


Em seg., 14 de nov. de 2022 às 17:58, Roberto Ierusalimschy <roberto@inf.puc-rio.br> escreveu:
> "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.
Postgres, per example, benefits from ARRAY_FLEXIBLE_MEMBER 0.

See at:
https://github.com/postgres/postgres/blob/master/src/include/c.h

#define ARRAY_FLEXIBLE_MEMBER            1

Lua 5.4.2 Windows (64 bits)
type sizes (bytes):
Struct                             Size
lua_State                        192
Proto                               128
Table                                 56
Udata                                48
CClosure                          48
TString                             40
Udata0                             40
UpVal                               40
LClosure                          40
Node                                24
NodeKey                          24
TValue                             16
GCObject                         16
Upvaldesc                        16


#define ARRAY_FLEXIBLE_MEMBER            0

Lua 5.4.2 Windows (64 bits)
type sizes (bytes):
Struct                             Size
lua_State                        192
Proto                              128
Table                                56
Udata                               32
CClosure                         32
TString                            40
Udata0                            40
UpVal                              40
LClosure                         32
Node                               24
NodeKey                         24
TValue                            16
GCObject                        16
Upvaldesc                       16

I was wrong, with ARRAY_FLEXIBLE_MEMBER 0, Lua reduces the structures by 16 bytes:
UData
CClosure

And, reduces the structure by 8 bytes:
LClosure