0

I am trying to understand why I am getting wrong sizeof for the below structure. My desired answer should be 12 but I am getting 16. Can you please explain what I am doing wrong?

struct dns_answer_section
{
    uint16_t name;
    uint16_t type;
    uint16_t class;
    uint32_t ttl;
    uint16_t data_len;
};
mazkopolo
  • 391
  • 1
  • 6
  • 21
  • 2
    There is this padding associated with the structs and there are many answers on SO . Please find the right one :) [sizeof struct](http://stackoverflow.com/questions/1841863/size-of-a-structure-in-c) – Gopi Apr 06 '16 at 10:30
  • 1
    http://www.catb.org/esr/structure-packing/ – Paolo Apr 06 '16 at 10:33
  • you can force the number of bit for a designated field in a structure by adding :number after the declaration of the field. (like uint16_t name:16;). Be warry that broke any optimisation made by the padding ... I can't really explain what I want because english is not my motherlanguage, so feel free to correct me. – Tom's Apr 06 '16 at 11:24
  • 1
    Move the `uint32_t ttl` to be the first field and there will be no padding. – Alex Lop. Apr 06 '16 at 11:40
  • `uint32_t` requires 4-byte alignment on your platform; and 2 bytes need to be added at the end of the structure to ensure that successive elements in an array have the `uint32_t` member aligned at 4 bytes as well. – Antti Haapala -- Слава Україні Apr 06 '16 at 12:10

0 Answers0