Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

241
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda