Skip to content

Adjust struct_size() to be more accurate with strange alignment/padding/etc #250

@kees

Description

@kees

Right now struct_size() will over-estimate in the cases where flexible arrays start within the struct (rather than exactly at the end). This isn't ideal, but is currently "just" a few bytes of extra space for allocations, etc. There is a risk of pathological problems, though, so it'd be better to make sure the macro can correctly handle weird structure layouts.

Perhaps something like this, adjusted to use size_mul(), size_add(), etc:

        if (offsetof(typeof(p), member) == sizeof(*p)) {
                /* flexible array exactly aligned at end of struct */
                size = sizeof(*p) + count * sizeof(*p->member);
        } else if (offsetof(typeof(p), member) < sizeof(*p)) {
                /* flexible array starts before end of struct */
                size = offsetof(typeof(p), member) + count * sizeof(*p->member);
                if (size < sizeof(*p))
                        size = sizeof(*p);
        } else {
                BUILD_BUG_ON(offsetof(typeof(p), member) > sizeof(*p));
        }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions