Search code examples
cstructurepadding

Why c-faq 16.7 solution does not consider padding bytes?


http://c-faq.com/strangeprob/ptralign.html

In 16.7, the author explains:

s.i32 = *(long int *)p;
s.i16 = *(int *)p;

will get into trouble 'cause these casted pointer may not be aligned. So he uses byte wise manipulation instead for solution.

My question is, since this code:

struct mystruct {
    char c;
    long int i32;
    int i16;
} s;

will have padding bytes after char c;, why didn't the author skip the padding when he try to get the long int i32;?


Solution

  • Keep in mind this is supposed to be a FAQ list. You have to read the Q and the A as if they were written by different people. Theoretically, the Q is something that actually gets Asked Frequently by people who don't know the answer. In reality it's probably not a direct quote from an actual question, but a sort of idealized version of the question made up by the FAQ list maintainter. But still, when writing the Q section the author adopts a different persona.

    In this case the questioning persona doesn't know about alignment or padding. He writes char buf[7] and the struct definition and thinks they should both be 7 bytes long. The 7-byte buffer is an external data format (in a file or a network protocol stream) that the questioner is trying to parse, the struct represents the variables he would like to parse it into, and the statements like s.i32 = *(long int *)p; are his unsuccessful attempt at doing it.

    In the A section, our author drops that persona and gives the correct method of transferring the data from the packed 7-byte buffer into the struct. He doesn't explain every detail of alignment and padding rules as applied to the struct and the char buffer because he wants to keep the answer brief.

    You're looking at a true old-style newsgroup FAQ list, which was designed to actually answer the questions that people ask frequently, not a corporate web-site style "FAQ" in which a marketing team makes up fake questions designed to flatter the company and avoid answering any complaints. (And does anybody else remember when there was a distinction between a FAQ which was a single question and a FAQL which was the FAQ List with answers? Where did that go?)