S
Steven Jones
Up until now, I was under the impression that when one talks about data
alignment, what one means is at what address some data is stored. For
instance, if we write
unsigned int x ;
assuming that sizeof(unsigned int) is 4 then &x will evaluate to some
address the value of which will be a multiple of 4. The reasoning is
analogous for the other fundamental data types supported by a given
compiler.
However, I recently came across the following:
unsigned short * p = (unsigned short *) str ;
where str has been defined as unsigned char * elsewhere, and points to
some data. str can point to an address with an arbitrary value, as far as
divisibility is concerned.
unsigned short x ;
unsigned short * y = &x ;
*y = p[0] ;
In my naivete, I thought that this last line would result in an unaligned
access whenever the address p is not a multiple of 2 (assuming that
sizeof(unsigned short) is 2) but my little test code shows that sometimes
it does, sometimes it doesn't.
Can anybody enlighten me here? What is the foolproof criterion to
determine is some data is correctly aligned?
alignment, what one means is at what address some data is stored. For
instance, if we write
unsigned int x ;
assuming that sizeof(unsigned int) is 4 then &x will evaluate to some
address the value of which will be a multiple of 4. The reasoning is
analogous for the other fundamental data types supported by a given
compiler.
However, I recently came across the following:
unsigned short * p = (unsigned short *) str ;
where str has been defined as unsigned char * elsewhere, and points to
some data. str can point to an address with an arbitrary value, as far as
divisibility is concerned.
unsigned short x ;
unsigned short * y = &x ;
*y = p[0] ;
In my naivete, I thought that this last line would result in an unaligned
access whenever the address p is not a multiple of 2 (assuming that
sizeof(unsigned short) is 2) but my little test code shows that sometimes
it does, sometimes it doesn't.
Can anybody enlighten me here? What is the foolproof criterion to
determine is some data is correctly aligned?