Yannick
Yannick

Reputation: 872

Struct offsets differ?

Normally I would have a good smile, but its so sneaky its not even funny. How the hell can a struct differ from one file to another?

I had a struct like this:

typedef struct pp_sig_s
{
          [...]
          int flags;
          size_t max;
          bool is_reversed;
        unsigned int sig[64];
          size_t byref;
          [...]
}
pp_sig_t;

It was defined in say "header01.h" Some function I use is in "program01.cpp" Declared this way

void PrintSig(pp_sig_t *s); // prints the content of sig[64] array in pp_sig_t for test purposes

Another object pp_sig_t called g_sig_1 was defined in "header02.cpp"... This .cpp includes of course header01.h I call the print routine this way inside it

PrintSig(&g_sig_1);

I notice the print result differs from the actual content. Say sig contains 0xE8, then it printed 0xE800

Then, I thought, about 2 hours of investigation, it could be struct alignment.

I try it...

Declaring the struct this way in header01.h

#pragma push()
#pragma pack(4)
typedef struct pp_sig_s
{
          [...]
          int flags;
          size_t max;
          bool is_reversed;
    unsigned int sig[64];
          size_t byref;
          [...]
}
pp_sig_t;
#pragma pop()

And suddenly everything works fine...

So basically its like if in program01.cpp the struct offsets were, i would guess, different than in program02.cpp...

How the hell can a struct differs from one file to another? How can we avoid this without using pragmas? Could it be called a compiler bug (i use Intel C++ XE Composer 2013 Update 2, on linux)?

Upvotes: 4

Views: 214

Answers (1)

microtherion
microtherion

Reputation: 4048

It seems likely that this was caused by an alignment pragma that was in scope when one of the files included the header, but not when the other did.

Upvotes: 1

Related Questions