problem with casting for arm compiler

Hi all
I have a strange problem when I'm trying to cast buffers by arm compiler.
Here an example:

char* pbuf;
...
unsigned short val = *((unsigned short*)(pbuf+3));


When I compile this code, my generated assembly code uses LDRH,STRH. Then because my pbuf+3 is not multiple of 2 and those 2 instruction can only work with even value addresses, processor hangs up.
What I should to do that compiler generates a code that works in all cases?

Regards

Parents
  • So don't do that, then!

    It is always risky to assume that you can just cast any arbitrary pointer to any other arbitrary type - precisely because this is likely to fall foul of the alignment rules of the underlying architecture.

    It is not a "strange" problem - it is rather to be expected!

    If you've got used to doing this on an 8-bit chip, then it has only been working by luck - because 8-bit processors just happen not to care about any alignment!

    You really need to do this "properly": pull the individual bytes out of the buffer and build them into the larger datatype.

    Either that, or you will have to somehow ensure that the bytes in your buffer are properly aligned to be accessed as the larger data type...

Reply
  • So don't do that, then!

    It is always risky to assume that you can just cast any arbitrary pointer to any other arbitrary type - precisely because this is likely to fall foul of the alignment rules of the underlying architecture.

    It is not a "strange" problem - it is rather to be expected!

    If you've got used to doing this on an 8-bit chip, then it has only been working by luck - because 8-bit processors just happen not to care about any alignment!

    You really need to do this "properly": pull the individual bytes out of the buffer and build them into the larger datatype.

    Either that, or you will have to somehow ensure that the bytes in your buffer are properly aligned to be accessed as the larger data type...

Children
More questions in this forum