Byte Alignment in C structure

Hello ,

I had a program which was crashing in HP IA 64 bit machine.
My program is configured for 4 byte alignment( #pragma pack(4)).
The same program didnt crash when configured for 8 byte alignment( #pragma pack(8))
Program was like this :

typedef enum comp
{
comp1=-1,
comp2,
comp3=0xFFFFFFF

}
typedef struct str1
{
comp nComp;
FunPtr nfunptr1;(Function pointer )
FunPtr nfunptr2;(Function pointer )

}str;

Structure str has a initialization as below :

str gStr[10]
= {
{comp(-1),mfunptr1,0L},
{comp(-1),mfunptr1,0L},
..
..
{comp(-1),mfunptr1,0L},
{comp(-1),mfunptr1,0L}

}

The above program used to crash.

But when i changed the code as below it didnt crash.
But i didnt understand why ?

typedef struct str1
{

FunPtr nfunptr1;/*Function pointer*/
FunPtr nfunptr2;/*Function pointer*/
comp nComp;
unsigned int PaddByte;/*Padding 4 byte*/

}str;



str gStr[10]
= {
{mfunptr1,0L},
{0L,mfunptr1,comp(-1)},
..
..
{0L,mfunptr1,comp(-1)},
{0L,mfunptr1,comp(-1)}

}


Please help me understand this ......

when you are uisng 64 bit mode, the struct is not having a perfect bit alignment.

in 64 bit, size of int (enum here) is 4 bytes, and size of pointer is 8 bytes.

The explicit addition of the padding is making sure that the structure str1 is aligend on a 8 bit alignment.

In the first case, gStr[0] is aligned as <------8 byte------> <------8 byte-------> <------4 byte----->
In the second case, gStr[0] is aligned as <------8 byte------> <------8 byte-------> <------8 byte----->

The second element gStr[1] is starting fine in the second case, following a strict 8 byte aligenment.
But in the first case, without the PaddByte, the element gStr[1] is sharing the last 4 bytes with the first element, which is causing inconsistency.

C++ Gurus, correct me, if iam wrong
Last edited on
I have these doubts :

1) when i aligned the 1st program for 8 byte alignment ( using #pragma pack(8)) without padding it didnt crash .... why ?
2) Why on 64bit machine struct is not having a perfect bit alignment ?
Topic archived. No new replies allowed.