3

I understand the idea that each scanline should have a number of bytes that is a multiple of 4. Otherwise, the BMP is stored in a such a way that each scanline is padded with as many zeros as it takes to extend that scanline's length to be a multiple of 4.

Later on pset 5 specifications page are these lines

Our use, incidentally, of the __attribute__ called __packed__ ensures that clang does not try to "word-align" members (whereby the address of each member’s first byte is a multiple of 4), lest we end up with "gaps" in our structs that don’t actually exist on disk.

I don't really understand what that means. Now,

  1. What does it mean that clang may "word-align" members of RGBTRIPLE?
  2. How would it do that?
  3. And why?
4

Word alignment is a performance optimization used by compilers. You can read a whole lot about it on Wikipedia: http://en.wikipedia.org/wiki/Data_structure_alignment.

This basically answers all 3 questions, but I'd like to mention why pset5 uses it. From the GCC documentation (http://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html):

This attribute, attached to [a] struct [...] specifies that each member of the structure or union is placed to minimize the memory required.

It simply tells the compiler to not attempt the optimization, as you want the RGBTRIPLE to be exactly as you have defined in the memory.

Hope this helps.

| improve this answer | |
  • So basically from what I get, for scanlines being having multiple of 4 bytes each, this has to do with the system as it reads from and writes to the memory in 4-byte chunks. Now I've got two more questions. First, who is responsible for adding these zeros to each scanline to extend its length to be a multiple of 4? And Second, if it's not the compiler, does __attribute__((__packed__)) basically prevents the compiler from performing a similar function (i.e., performing data structure padding as denoted by the wikipedia article)? – Kareem Jun 23 '14 at 13:22
  • 1
    @Kareem It is important that this is no one's responsibility, it is a feature offered by the compiler. As you have said; by specifying the __packed__ attribute, you are essentially telling the compiler not to attempt this optimization. – skreborn Jun 23 '14 at 13:31
  • So I'm already telling it not to perform data structure padding I assume because it's already performed! Or where do these zeros come from when the scanline doesn't have a multiple of 4 number of bytes? – Kareem Jun 23 '14 at 13:41
  • @Kareem The specification also says that the "order does matter when it comes to struct's members". The bytes in the file are in BGR order, so you need the struct's members to be in the exact same order. The optimization (that you prevent by using __packed__) may switch these members, resulting in the incorrect reading of the colors. – skreborn Jun 23 '14 at 13:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .