0

I have a question regarding memory alignment in C language and microcontrollers. For A 32bit word size microcontroller I understand that a 4 byte variable should be aligned at an address multiple of 4 for easy access of words . Similarly with 2 byte variables should be aligned at an address multiple of 2 for easy access of half words.

But I can't really seem to understand why 8 byte variable should be aligned at an address multiple of 8 ?! the processor will already load it on 2 steps loading each word individually then why it shouldn't be on a 4byte alignment addresses ?! for example

typedef struct
{
    uint8_t x;
    uint64_t y;
}m;

why it's size is 16 bytes and not 12 what is the reason behind making it an 8 byte alignment even if my word size is only 4Bytes ?! Thanks in advance

  • *why 8 byte variable should be aligned at an address multiple of 8* - where did you get it from? In general, hardware might or not require aligned access. Sounds like you are asking about `struct` alignment based on it's largest member type. But this is C requirement, not the hardware. – Eugene Sh. Apr 28 '22 at 13:13
  • Discussed at length elsewhere https://stackoverflow.com/questions/55920103/why-is-the-alignment-the-same-on-32-bit-and-64-bit-systems. I doubt anything new will be added by answering the his question. – Clifford Apr 28 '22 at 13:20
  • Thanks for your Comments guys it was really help full. @EugeneSh. yes I was Wrong its C Requirement but why should it based on it's largest member type ?! I read because if an array is created then all elements shall be aligned as well but if it was according to the word size won't that make all elements of an array aligned as well ?! isn't that a waste of memory space on 32bit microcontrollers ?! or am i missing something ?! – Abdelrahman Mahmoud Apr 28 '22 at 14:01

0 Answers0