Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

239
Views
Troubles while reading the struct size

If I debug the following code then I see the size value is 12 (as expected).

#include <cstdint>

int main(int argc, char *argv[])
{
    typedef struct __attribute__((__packed__))  { int8_t value; } time;

    typedef struct __attribute__((__packed__))  {
        uint8_t msg[8];
//        time t1;
        uint32_t count;
    } theStruct;

    theStruct s;
    int size = sizeof(s);

    return 0;
}

Interestingly, removing the comment at "time t1;", the value of size goes to 16. I was expecting 13.

I know (more or less) that this is explained by the data structure padding story...

But, is there some way to avoid this issue? What to do in order to read size = 13?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

There are some issues with MinGW's emulation of MSVC struct packing.

The workaround is to pass -mno-ms-bitfields flag to the compiler; this will cause it to use its own layout algorithm rather than attempt to emulate MSVC.

See also Struct packing and alignment with mingw (ARM but may be the same issue).

over 4 years ago · Santiago Trujillo Report

0

It is clearly an alignement problem, meaning it has nothing to do with the language itself but all with the underlying platform.

If the platform knows (or thinks) that int32_t need an alignement of 4, it should add 3 bytes of padding after time.

Anyway __attribute__((__packed__)) is non standard C and will only be interpreted by gcc (*). Worse it leads to non portable programs : according to this answer on another question, it would cause a bus error on a Sparc architecture because of a misaligned int32_t.

I do know that x86 (and derivatives) architecture are now the most common, but other architecture may still exist ...

(*) according to Visual C++ equivalent of GCC's __attribute__ ((__packed__)), the MSVC equivalent is #pragma pack(push, 1)

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!