Message Edited by fiskom on 2007-02-0709:50 AM
Lundin wrote:
Call it a bug or oddity or whatever you like, it is an unexpected behavior of the program caused by the compiler.
...
And what happens? The code looped 4 times and wrote to the two hardware registers located after A and B and caused a nuclear meltdown. The programmer has done nothing wrong: he knows that the cpu he is using can address variables at even 16-bit address. The compiler port to the specific processor is faulty.
Steve.
sjmelnikoff wrote:Safe options for using unions are:
- Use them only for sharing memory space, where the overlapping areas are used for different things at different times. In other words, don't use unions to access the same data in two different ways (as done in the above example).
- If you use them in the manner described above, read the compiler manual to make sure you understand how they will be implemented.
Steve.
On the contrary; the programmer should not have to worry about things like that - unless it becomes relevant, as the above examples demonstrate.Lundin wrote:Yes, on most cpu:s misaligned bytes will take a few ticks longer to access, but if the programmer is concered about that, he can allocate the variables manually at even locations in his memory map.
Lundin wrote:
He is writing in C after all, so it can't be a big issue since most of the variables will end up on the stack anyway.
bigmac wrote:If using a union cannot be safely used to "access the same data in two different ways", I am wondering what are the safe alternatives?...If this cannot be guaranteed, what are the alternatives?