structure padding in C++

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

Expert Comment

ID: 19553662

Author Comment

ID: 19553701
yes, sizeof, how to calcualate?
LVL 43

Expert Comment

ID: 19553817
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.
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

LVL 39

Expert Comment

ID: 19553927
>>>> 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

ID: 19554019
>> 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

ID: 19557679
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 ) );  }


Expert Comment

ID: 19566916
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

ID: 19596978
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.

Expert Comment

ID: 19606472
agreed with krusho this technique is uesd to avoid the wastage of memory in structure

Accepted Solution

aatrish2001 earned 2000 total points
ID: 19606492
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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
Suggested Courses

862 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