At 10:22 PM 12/16/05 +0100, Marko Panger wrote:
>I have a general programming question. Me and my co-workers had an
>discussion about data alignment and non-aligned accesses. Please
>consider the following situation where an un-aligned access was made
>resulting in wrong value.
>
>char buf[5] = {1,2,3,4,5};
>unsigned short tmp;
>
>tmp = *(unsigned short*)&buf[1]; /* &buf[1] is on a odd address
>
>My co-workers expected that tmp will contain the value0x0203, but the
>value was 0x02. I understand that, because ARM7 core does not support
>un-aligned accesses and the compiler was forced to use a word access on
>a odd address. This code was ported from an 8-bit machine where it was,
>off course, working. My question is if all 32-bit devices would have the
>same problem with this code and why when we tested the same situation on
>a PC using Borland Builder compiler it was working as my co-workers
>expected. Is this a CPU(+cpu bus) issue or it is also compiler dependent.
Compiler, micro and possibly more could play a role. ANSI and ISO give the
compiler leeway to do just about anything at this point. Some micros will
have a bus fault, some will read the incorrect value and some will read the
'correct' value. Note that whether the problem shows up may also depend on
what else is in memory since the compiler is certainly free to place buf
such that it starts on an odd address at which point buf[1] is suddenly on
an even address. Of course on a recompile it might change. All of a
sudden you have yourself a Heisenbug.
The correct value at this point is also open to question even if alignment
isn't an issue since that still leaves byte ordering and that varies across
micros.
>Although I thing this is bad programming practice and it calls for
>errors I am asking if it is possible to enable a warning for such
>situations.
Yes, but the cast will likely trip you up. PC-Lint gives me a warning
about a cast from a pointer to a pointer but that is probably not a
sufficient warning.
Depending on what you are trying to do there are alternatives that will
work reasonably portably.
Robert
" 'Freedom' has no meaning of itself. There are always restrictions, be
they legal, genetic, or physical. If you don't believe me, try to chew a
radio signal. " -- Kelvin Throop, III
http://www.aeolusdevelopment.com/Message
Re: [lpc2000] Un-aligned data access on ARM7 core
2005-12-17 by Robert Adsett
Attachments
- No local attachments were found for this message.