lua-users home
lua-l archive

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


"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;
}



On Sun, Nov 13, 2022 at 6:02 AM Ranier Vilela <ranier.vf@gmail.com> wrote:
Lua could benefit from introducing ARRAY_FLEXIBLE_MEMBER define.

With C99 or greater, struct with array flexible member can be:

struct STRING_S
{
    size_t size;
    char data[];
};

Before C99, I think maybe it needs to be used with zero,
I haven't checked.
struct STRING_S
{
    size_t size;
    char data[0];
};


x86_64 plattform -O2
#include <stdio.h>

struct STRING_S
{
    size_t size;
    char data[1];
};

typedef struct STRING_S string_t;

int main(void)
{
    string_t str;

    printf("size=%zu\n", sizeof(str));

    return 0;
}

ASM generation compiler returned: 0
Execution build compiler returned: 0
Program returned: 0
size=16

So, some structs can be reduced by 8 bytes.

struct Udata
struct CClosure
struct LClosure


--