Skip to content

Use offsetof for flexible struct allocation #390

@edongashi

Description

@edongashi

We are doing allocation of structs with flexible array members wrong. It should be:

palloc( offsetof(MyStruct, last_member) + num_items * sizeof(ArrayMember) );

See https://github.com/postgres/postgres/blob/master/src/include/c.h#L342-L350.

The reason is that padding may give a different array start location compared to sizeof.

typedef struct MyStruct {
    double x;
    char y;
    int z[];
} MyStruct;

int main(void) {
    printf("sizeof: %lu\n", sizeof(MyStruct));
    printf("offsetof: %lu\n", offsetof(MyStruct, z));
}

The above prints:

sizeof: 16
offsetof: 12

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions