structure padding
Started by Cibressus, Sep 12 2004 01:29 PM
11 replies to this topic
Sponsor:
#2 Members - Reputation: 1258
Posted 12 September 2004 - 01:32 PM
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
there are ways to turn off the padding in your code, just google for it if you truly care.
-me
#3 Staff Emeritus - Reputation: 1668
Posted 12 September 2004 - 01:35 PM
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.
#8 Moderators - Reputation: 1918
Posted 12 September 2004 - 01:46 PM
Ok, heres an example:
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.
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.
#11 Members - Reputation: 97
Posted 19 February 2013 - 01:38 AM
structure padding matters most when alignment matters, which helps in potential performance and avoids any possible bus errors, please refer
http://www.refcode.net/2013/02/structure-padding-explained.html
This topic is locked






