domenica 28 febbraio 2010

Padding and rearranging structure members

Here's what C and C++ compilers must do to keep structure members aligned.

http://www.embedded.com/217200828

2 commenti:

  1. Padding between adjacent structure members is called internal padding. Padding after the last member is called trailing padding. The C Standard doesn't allow leading padding. It specifically states that "A pointer to a structure object, suitably converted, points to its initial member and vice versa. There may be unnamed padding within a structure object, but not at its beginning."2

    Each structure object must be at least as a strictly aligned as its most strictly aligned member. For example, the most strictly aligned member in widget is integer m2, which is word aligned. However, the m2 member of an actual widget object won't be word aligned unless that widget object is also word aligned. Thus each widget must be at least word aligned. A compiler could decide to make widget double-word aligned, which it might do if the stricter alignment yielded faster memory access. (I'm just speculating here. I don't know of a compiler that actually does this.)

    RispondiElimina
  2. Rearranging members to reduce padding
    You can reduce the size of each widget by rearranging the members to reduce the number of padding bytes. Specifically, you can rearrange the member declarations so that the char members m1 and m3 are adjacent to each other, as in:

    struct widget
    {
    char m1;
    char m3;
    int m2;
    };

    In this case, the compiler will add only two padding bytes, as if you had declared widget as:

    struct widget
    {
    char m1;
    char m3;
    char padding[2];
    int m2;
    };

    Consequently, sizeof(widget) would be only eight, rather than 12. (Again, I'm calculating these sizes assuming an int is a 4-byte object aligned to an address that's a multiple of four. The sizes could be different on a machine with different object sizes and alignment requirements.)

    You can rearrange widget's members in other ways to reduce the number of padding bytes. For example, defining widget as:

    struct widget
    {
    int m2;
    char m1;
    char m3;
    };

    also reduces the number of padding bytes to two and sizeof(widget) to eight.

    A Standard C compiler won't rearrange the members of a structure automatically to reduce the structure's size. According to the Standard: "Within a structure object, the non-bit-field members ... have addresses that increase in the order in which they are declared." This effectively prohibits compilers from rearranging structure members from the order in which they're declared.

    RispondiElimina

Nota. Solo i membri di questo blog possono postare un commento.