Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use offsetof for flexible struct allocation #390

Open
edongashi opened this issue Jun 27, 2022 · 2 comments
Open

Use offsetof for flexible struct allocation #390

edongashi opened this issue Jun 27, 2022 · 2 comments

Comments

@edongashi
Copy link
Member

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
@cristianberneanu
Copy link
Collaborator

cristianberneanu commented Jun 27, 2022

It doesn't look to me that we have a problem: sizeof(MyStruct) is always greater than or equal to offsetof(MyStruct, z), so, in the worst case, we just waste the padding bytes.

@edongashi
Copy link
Member Author

edongashi commented Jun 27, 2022

You're right. For a moment I saw it the other way around. Nonetheless, it's a good small fix to have.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants