Sign in to follow this  

structure padding

This topic is 1759 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

structure padding makes structures a multiple of 32 bits. this is because your processor is super fast at dealing with things in those multiples and slower otherwise. it effects sizeof because the sizeof will be in multiples of 32 bits even if what you coded isn't. in general it's best to just let the padding be there. you will otherwise just slow down your app a bit. the amount of memory "lost" is probably insignificant for what you're doing.

there are ways to turn off the padding in your code, just google for it if you truly care.

-me

Share this post


Link to post
Share on other sites
Structure padding is the use of environment- and platform-specific options to "round out" the sizes of POD structures to, say, multiples of 4 bytes. It is problematic for sizeof because it is external to the code itself. It can also be problematic for data intended to be transmitted over a network.

Share this post


Link to post
Share on other sites
Ok, heres an example:

struct Foo
{
int n1;
char ch1;
int n2;
};


Now, assuming the compiler pads to 4 bytes, and that an int is 4 bytes and a char is 1, that structure will be 12 bytes long. The first int takes up 4 bytes, and then the 5th byte is taken up by ch1. The compiler then puts 3 bytes of padding in after that, so that n2 is aligned to a 4 byte boundary. That should (in theory) make it faster to access n2.
However, if you're reading and writing this structure to a file, you probably don't want padding, since you expect to read 9 bytes - not 12. So you would disable padding for this structure.

Share this post


Link to post
Share on other sites
Sizeof will account for padding. Don't disable it as some systems require alignment, and worse of all, it prevents almost all optimizations that the compiler can perform.

Share this post


Link to post
Share on other sites

This topic is 1759 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Guest
This topic is now closed to further replies.
Sign in to follow this