Structure alignment problem in Cosmic cross compiler for MC9S12DP256

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Structure alignment problem in Cosmic cross compiler for MC9S12DP256

2,987 Views
Rathnam
Contributor I
Hello All,
 
I am using Cosmic C compiler for MC9S12DP256 (16 bit microcontroller)  in my project.
 
I am facing the following problem
 
typedef struct {
unsigned char Var1[182];  // 182 bytes
unsigned long  Var2;         // 4 bytes
unsigned char Var3[16];   // 16 bytes
}ABC;
 
As you see here this structure should take 202 bytes of memory , but when i use sizeof(ABC) --> it returns 204
 
my doubt is, even though the elements in this structure is align to even position, why the compiler is padding 2 more bytes extra?
 
Thanks and regards - Rathinavel
Labels (1)
0 Kudos
2 Replies

507 Views
Obetz
Contributor III
Hello Rathinavel,

compiling your code yields a struct size if 202 as you expected.

I suggest to ask Cosmic directly or post your question again in the mailing list [1] where Cosmic reads also.

Oliver

[1] http://groups.yahoo.com/group/68HC12/ - you don't need a Yahoo! account, send a blank mail to the subscription address.
0 Kudos

507 Views
mjbcswitzerland
Specialist V

Hi Rathinavel

Presumably the compiler is putting var2 to start at an aligned long word boundary and so skipping 2 bytes at the end of the Var1 array. Normally there will be a compiler setting allowing you to define whether long words are aligned to such boundaries.

If the exact ordering of the variables in the struture is not critical you could also put the long word variable to the top of the structure so that it is started at an aligned address and the bytes of the following arrays will not have to be aligned. This is a general programming tip for processors where the alignment is fixed and can not be controlled by the compiler - start structures, local variables etc. in the order largest first und finish with smallest (bytes) so that the compiler can make the best of the memory space without unnecessary holes.

Regards

Mark Butcher
www.mjbc.ch

 

0 Kudos