0

Is it dangerous/risky to use #pragma pack(1) on structs that contain byte-arrays only? E.g. this one:

#pragma pack(1)
struct RpcMessage {
    uint8_t proto_info[16];
    uint8_t message_uuid[16];

    uint8_t arg0[16];
    uint8_t arg1[16];
    uint8_t arg2[16];
    uint8_t arg3[16];
    uint8_t arg4[16];
    uint8_t arg5[16];
    uint8_t arg6[16];
    uint8_t arg7[16];

    uint8_t payload[65376];
};

(The idea is to cast this struct directly to/from 2^16 raw I/O bytes without any incompatibilities or even faults)

K. Biermann
  • 1,295
  • 10
  • 22
  • 2
    There's no risk or danger per se; it's just unnecessary. If everything is an array of bytes, there'll be no padding between the elements anyway, so the pragma is pointless (harmless, but pointless). – Jonathan Leffler Oct 24 '18 at 14:00
  • The only problem with packing, that I know of, is making unaligned transfers which increase the number of necessary assembly instructions. – Fiddling Bits Oct 24 '18 at 14:01
  • @FiddlingBits: The alignment requirement of the struct is already 1 on any reasonable ABI, so it's not going to make any difference. – R.. GitHub STOP HELPING ICE Oct 24 '18 at 14:42
  • @R Right. Should have mentioned if greater than one byte. – Fiddling Bits Oct 24 '18 at 14:43
  • pragma's and attributes are an abomination, and should only be used when absolutely necessary. They convert the C Language -- a well enough designed language to mostly survive attacks by standards groups -- into a language of your own design. – mevets Oct 24 '18 at 15:21

2 Answers2

4

If the structure only contains uint8_t, then #pragma pack(1) will have no effect at all. It simply won’t do anything, because the structure is already packed as tightly as it can be.

Padding will only appear if you have elements which have larger than byte alignment.

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
  • 2
    This isn't necessarily true in case of `uint8_t x [3]; uint8_t y [n];`. The compiler might want to allocate `y` on an aligned address for better performance, in which case it is free to insert padding between `x` and `y`. – Lundin Oct 24 '18 at 14:04
  • 1
    @Lundin: Perhaps this is technically true, but it would be a clear sign that the people who designed your compiler hate you, and want to see you fail. – Dietrich Epp Oct 24 '18 at 14:16
  • To my knowledge, what @Lundin claimed is not true on any ABI in modern use. – R.. GitHub STOP HELPING ICE Oct 24 '18 at 14:42
  • Me neither, it is just one of those theoretical, language-lawyer comments :) Although one need not look far to find the case where the compiler likes to allocate arrays on aligned addresses: just look at local variables. – Lundin Oct 24 '18 at 14:44
2

Given that each array has a size which is a multiple of the alignment, #pragma pack won't do anything, as each array will automatically be properly aligned.

Lundin
  • 195,001
  • 40
  • 254
  • 396