structure padding in C++

Posted on 2007-07-23
Last Modified: 2012-05-05
structure padding in C++?  calcualated? thanks
Question by:joinsaigon
    LVL 84

    Expert Comment


    Author Comment

    yes, sizeof, how to calcualate?
    LVL 43

    Expert Comment

    struct Whatever
     int something;

    Whatever varName
    cout << sizeof(Whatever) << " " << sizeof(varName) << endl;

    But it explains how to obtain memory usage for single object (but pointers are not dereferenced).

    About padding? What You exacltly want to know? Note, that various compilers do different paddings on same structures.
    LVL 39

    Expert Comment

    >>>> Note, that various compilers do different paddings on same structures.
    You can avoid that by forcing your compiler to make single-byte alignment. You normally do it in the project settings but there are compiler switches (VC: /RTC1) or preprocessor (#pragma pack)  directives as well.

    Another approach to avoid padding is to order members by type: double, all kind of pointers, float, all kind of int32, all kind of int16 (short), all kind of char. If using arrays make the size a multiple of 4. If using member structs the ordering rules apply as well and it should be sized a multiple of 4. Then struct members can be added between double and all other types.

    Regards, Alex

    LVL 53

    Expert Comment

    >> structure padding in C++?  calcualated? thanks

    What's the question ? Do you want to know how much padding is added to a struct ? If so, the sizeof operator will allow you to get that information (as already suggested). If you're looking for something else, then can you explain what ?

    Here's an example of what you could do :

            struct myStruct {
                int i;
                char c;
                bool b;
                float f;

            int padding = sizeof(myStruct) - sizeof(int) - sizeof(char) - sizeof(bool) - sizeof(float);

    padding will contain the number of bytes that are added as padding to the myStruct struct.
    LVL 22

    Expert Comment

    There is no STANDARD way to estimate or calculate how structure fields get packed.

    Compilers are free to do whatever they want as long as the code still behaves the same.

    One way, about the only way to figure out packing is by comparing the size of each field with the addresses it spans.

    For example, something much like (UNTESTED)  this:

    typedef   struct { int f1, f2, f3, f4; char f6; float f7; char f8; }  MyStruct

    MyStruct S;

    #define Sz(f)  sizeof(f)

    #define Span( fa,fb )   ( (int)    ( ( char *) S.fb ) -   (char * ) (&S.fa) ) )

    #define PaddingBetween(x,y)  (  Span(x,y) - Sz( x ) )

    main () {  printf( "%d", PaddingBetween( f6, f7 ) );  }

    LVL 1

    Expert Comment

    Varies compilers has different options and #pragma to control padding that's done.  In your compiler's documentation, search for "pack" and you *should* get documentation on what the default packing is and the varies option to change that.

    #pragma pack(1)
    class A {
    char a;
    int b;
    double c;
    #pragma pack(pop)

    p.s. #pragma pack are handled differently by each compilers.  For example, GCC's is a stacking way with some global switch, this could be a gotcha when you try to use it.

    Expert Comment

    I know if you do something like

    struct Blah
          int a      : 1;
          int b      : 1;
          int c      : 14;
          int d      : 1;
    } Blah_t;

    It will pad this out to 32 bits since 'd' is only using 1 bit but nothing else can fit in the remaining 15 the code will just pad it.
    LVL 3

    Expert Comment

    agreed with krusho this technique is uesd to avoid the wastage of memory in structure
    LVL 3

    Accepted Solution

    Its common for structures to have external padding as well as internal padding. This is
    required to ensure that alignment properties are preserved when an array of contiguous
    structures is allocated. Even if the structure is not part of an array, the end padding
    remains, so that sizeof() can always return a consistent size.

    Featured Post

    What Security Threats Are You Missing?

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    Join & Write a Comment

    Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
    Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
    The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.
    The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…

    732 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    19 Experts available now in Live!

    Get 1:1 Help Now