I'm using x86 intel machine, and windows 7, plus Visual C++ (versions 2005/2012 express)
I have been playing with alignment (I have just been doing this as a learning exercise.) Certainly I understand the implications on the size of the class/struct in terms of padding. I believe that I understand that it is also better aligned because of the way that CPU instructions work and expect data.
I have been looking at many different resources generally, for example (interesting) c++ data alignment /member order & inheritance (and other links like wikipedia) http://en.wikipedia.org/wiki/Data_structure_alignment
One area that can be affected (I read) seems to be performance, due to the need for data to be specific sizes for registers, misaligned data can cause issues (see wikipedia).
I wrote some code in which I created 3 structs, all with the same members with packing set to 1 , normal alignment, and with the members rearranged. This gave me objects with sizeof 8, 10 and 12. I ran code similar to the following for each :
struct MixedData1
{
char Data1;
short Data2;
int Data3;
char Data4;
void operator() (MixedData1& md)
{
md.Data1 = 'a';
md.Data2 = 1024;
md.Data3 = 1000000;
md.Data4 = 'b';
}
};
typedef std::vector<MixedData1> MDVector;
int main(int argc, char* argv[])
{
MixedData1 md;
for(int count = 0; count < 10 ; count++)
{
{
std::cout << sizeof(md) << std::endl;
boost::timer::auto_cpu_timer t;
MDVector mdv(10000000);
std::fill(mdv.begin(),mdv.end(),md );
std::for_each(mdv.begin(),mdv.end(),md);
}
}
}
I'm not really interested in the values so each element in the vector is initialised the same. Anyway I got results that indicated that the running time increased with the size of the struct - I.E with pack(1) (8 bytes) I got the quickest 0.08s, and with normal alignment (12 bytes) I got the slowest 0.105 .
My questions are about the effects of being wrongly aligned. I don't think I have ever had any issues with alignment throughout my X years as a C++ programmer, but of course it could have just passed me by.
(1) The alignment had an effect (I believe) in my test (edit) however as Neil posted it was only due to the difference in struct size. I tried accessing the member as per his reply but I saw no real effect there.... is there a clearer example? Is there a way I can see a dramatic effect of misalignment? (2) Is there a way to induce a crash caused by misalignment if possible.