cancel
Showing results for 
Search instead for 
Did you mean: 

Memory alignment of STM32

suppakit
Associate II
Posted on February 21, 2014 at 08:45

Hi, every one.

I create this structure. Then I try to find size of this structure. But it seem wrong.

typedef struct {

    uint8_t  a;

    uint8_t  b;

    uint16_t c;

    uint16_t d;

    uint8_t  e;

} test;

sizeof (test) = 8

Normally, it should be 7. Why is 8?

I try to check about the memory alignment in ldscript.

That is 32 bits =>   ''. = ALIGN(4);''.

How can I get the actual size of this structure?

Thank you
2 REPLIES 2
chen
Associate II
Posted on February 21, 2014 at 10:30

Hi

I do not have an exact answer for you.

''I try to check about the memory alignment in ldscript.

That is 32 bits =>   ''. = ALIGN(4);''.''

I do not think the linker alignment is anything to do with your question.

The linker alignment is mainly about making sure the executable and the initialised variables are correctly aligned in memory.

I think it may depend on where the data structure is being created.

If it is a local variable - then it is on the stack. I think this must be aligned to 2 or 4 byte.

If it is malloced/newed - then it is in the heap. The memory space in heap is normally larger than asked for (have a look at the malloc implementation from Linux).

I think the key to answer your question is how sizeof() works. I could not easily find the answer but wikipedia alludes to the answer :

http://en.wikipedia.org/wiki/Sizeof

Under 'Structure padding' is says

''Therefore, compilers usually align data structures to at least a

http://en.wikipedia.org/wiki/Word_%28data_type%29

alignment boundary, and also align individual members to their respective alignment boundaries''

So in your case, the last uint8_t is actually moved along 1 byte ie padded - so giving your answer as 8 instead of 7.

Posted on February 21, 2014 at 11:13

Compiler structure packing != Linker section alignment

An extra pad byte is added to the end so that an ARRAY of the structure will be properly aligned.

Want to adjust the packing?

http://gcc.gnu.org/onlinedocs/gcc/Structure-Packing-Pragmas.html

http://en.wikipedia.org/wiki/Data_structure_alignment

https://www.google.com/search?q=gcc+structure+packing

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..