Alignment and padding in C

Viewed 138

I have problem with alignment and padding. My linker script (part of this) looks somthing like this:

MEMORY
{
  ....
  ....
  ....
  RAM_BUFF    (RWX) : ORIGIN = 0x20012000, LENGTH =  24K 
}


  .buffer :
  {
    . = ALIGN(2);
    __buffer_section = .;
    KEEP(*(.bufferhead))
    KEEP(*(.bufferentry))
    KEEP(*(.buffercirc))
    . = ALIGN(2);
    __buffer_section_end = .;
    __bufferr_section_size = __buffer_section_end - __buffer_section;
  } > RAM_BUFF

In this sections I have created some structures, variables and arrays in different parts of code. On one place I have somthing like this:

__attribute__((section (".bufferhead"))) bufferstruct BUFF_header;
__attribute__((section (".bufferentry"))) int16_t BUFF_entry;
__attribute__((section (".buffercirc"))) int16_t BUFF_circular[1 * 10];

With this I have no problem with memory organization. When I compile program, my .map file (part of it) looks like this:

*(.bufferentry)
 .bufferentry   0x200120d0       0x14 BUFFBEG.obj
                0x200120d4                BUFFSTART_entry
                0x200120d6                BUFF_entry
                0x200120d8                BUFFEND_entry
                0x200120e4                . = ALIGN (0x2)

Variable BUFFSTART_entry (int16_t) is on address 0x200120d4 (takes 2 bytes) and BUFF_entry (int16_t) on address 0x200120d6 (takes 2 bytes) and everything is OK.

When I put an array with one int16_t memeber BUFF_entry[1] instead of variable:

__attribute__((section (".bufferhead"))) bufferstruct LOGGARI_header;
__attribute__((section (".bufferentry"))) int16_t BUFF_entry[1];
__attribute__((section (".buffercirc"))) int16_t BUFF_circular[1 * 10];

my .map file looks completely different:

*(.bufferentry)
 .bufferentry   0x200120d0       0x18 BUFFBEG.obj
                0x200120d4                BUFFSTART_entry
                0x200120d8                BUFF_entry
                0x200120dc                BUFFEND_entry
                0x200120e8                . = ALIGN (0x2)

Variable BUFFSTART_entry(int16_t) is on address 0x200120d4 (takes 4 bytes) and array BUFF_entry[1] (int16_t) on address 0x200120d8 (takes 4 bytes).

Why, when I put int16_t array with one member instead of int16_t variable, I have this alignment and how can I prevent this (to get first example where takes 2 bytes)?

0 Answers
Related