2

Generally a short variable must be at 2-byte align address, but is there any problem if I try to point it at an odd address?

I try this code on VC++ 2008 and it runs properly so can you explain why?

    unsigned char ca[10];
    unsigned short *s1 = 0;
    memset(ca, 1, 10);

    s1 = (unsigned short*)&ca[0];
    printf("s1 = %d\n", *s1);
    s1 = (unsigned short*)&ca[1];
    printf("s1 = %d\n", *s1);

In the code snippet above, ca[0] or ca[1] there is one certainly at the odd address, so it is not 2-byte alignment, but s1 is perfectly assign to both ca[0] and ca[1].

So is this code correct as expected and is it recommended to do it this way? I would like to have a portable method that read any two bytes in an byte array as a short variable to work well in almost all platforms/compilers.

Thank you very much.

Mysticial
  • 464,885
  • 45
  • 335
  • 332
longbkit
  • 1,218
  • 1
  • 13
  • 20
  • 2
    http://stackoverflow.com/questions/1496848/does-unaligned-memory-access-always-cause-bus-errors might provide some useful background information here... – reuben Jul 05 '12 at 06:27
  • 1
    What you have right now is definitely not portable nor safe. Pedantically speaking it's actually UB. The reason why it works in your case is because x86 allows misaligned memory accesses. – Mysticial Jul 05 '12 at 06:28
  • 1
    Alignment aside, there's also the issue of endianness... – Mysticial Jul 05 '12 at 06:31
  • 1
    I still remember that when I made this error in the early 90's, the application would crash on Unix systems with a 'Bus Error'. x86 systems allow this, but at a speed cost. – Patrick Jul 05 '12 at 06:32

1 Answers1

4

There is no "must", it's just something the CPU can or cannot do. x86 in particular is probably able to do "misaligned" accesses, although it's almost sure to be less efficient.

Portability to other CPU architectures may or may not be something you care about, but misaligned memory access should generally be avoided. Plus, you pretty much have to fool the compiler into even letting you do misaligned stuff... like you begging it "please, please, please, but I really want to shoot myself in the foot, please let me do it"'; it's not generally something you can do accidentally.

Christian Stieber
  • 9,954
  • 24
  • 23