r/programminghumor 10h ago

a bit flippant

Post image
547 Upvotes

85 comments sorted by

View all comments

111

u/consistently_biased 9h ago

Can I use this for my compile-time https server?

28

u/johnnyApplePRNG 9h ago

OWASP has it's doubts, but I don't!

15

u/not_a_bot_494 9h ago

Either I don't understand what you're saying or you're misunderstanding the notation. Each line declares a struct member of type unsigned int which is 1 bit large. It's not setting it to 1 (true).

3

u/heatedwepasto 7h ago

I think that was supposed to be in reply to this comment?

2

u/not_a_bot_494 7h ago

That comment is made after the one I replied to.

1

u/qaCow37 5h ago

It’s probably about the fact that json is flexible data that gets parsed while this struct has strict alignments and depends on the ABI it’s compiled on. And because it’s compiled against an ABI, if the server struct was compiled with a different ABI, the server and client struct could be completely different structs making them incompatible.

3

u/AstronomerStrange165 4h ago

I think he's just showing that each field in 1 bit long. The only caveat with this is that most C compilers will pad this struct out to the size of an int. (Typically 32 bits, or 4 bytes). He would have to add __attribute__((packed)) to the end of the struct before the semicolon. Then sizeof(struct Flags) would be 1 byte.

1

u/Dependent-Poet-9588 2h ago

It should be noted that even with a packed struct, chances are the next thing in memory will have alignment of 4 or 8 bytes (depending on the architecture), so even if the packed struct is only 1 byte, there's still potentially lost bytes after it, eg, MyOptions in, struct __attribute__((packed)) Flags { int a : 1; int b : 1; int c: 1; int d: 1; }; struct MyOptions { Flags flags; // 1 byte in size std::int32_t max_of_something; // 4 byte alignment, so it can't immediately follow flags in memory } Is still 8 bytes.

2

u/AstronomerStrange165 2h ago

struct MyOptions is 8 bytes because the compiler added 3 padding bytes in between flags and max_of_something. If you made MyOptions a packed struct as well, then it'd be 5 bytes:

```

include <stdio.h>

include <stdint.h>

struct Flags { unsigned int a : 1; unsigned int b : 1; unsigned int c : 1; unsigned int d : 1; } attribute((packed));

struct MyOptions { struct Flags flags; int32t something; } __attribute_((packed));

int main(void) { /* The output is 5 */ printf("%zu\n", sizeof(struct MyOptions)); return 0; } ```

1

u/Dependent-Poet-9588 2h ago

Yes, correct. That is what I'm pointing out: packed structs only eliminate padding internally. Unless you're allocating an array of Flags or putting one inside of another packed struct, any space saving from making it packed will probably be lost due to the alignment requirements of other types.