0

I am working on some C code for a 16 bit microcontroller. When I debug the application on target I end up hitting an AddressError ISR. I read the data sheet and it says that this can happen if you try to read or write to a 16bit value that is aligned at an odd memory address. I think I understand what that means, but it just doesn't seem right. Wouldn't mean that if I were to make a struct like this:

struct foo{
    uint8_t thing1;
    uint16_t thing2;
};

that I would never be able read or write to thing2 without an error? If not, does that mean the compiler will automatically pad 8 bits between thing 1 and thing 2 so that thing two is aligned properly on an even address? If that is the case, then how would an address error ever occur?

PICyourBrain
  • 9,976
  • 26
  • 91
  • 136
  • 4
    You probably need to add more detail to the question. But check the alignment in your compiler to make sure it's aligning to 16 bits. With alignment the above struct would work. – PeterJ Dec 14 '12 at 04:38
  • Check your processor manual, to see what addresses are legal. Then check your linker command file. – anishsane Dec 14 '12 at 05:37

3 Answers3

0

Most small footprint processors allow only a limited set of memory operations, as misaligned memory reads would have to be completed in two or more cycles and increase the overall complexity of the processor.

This doesn't often show in c code, as both stack variables and struct members are aligned to the native width of the type (or 4 or 8 bytes, whichever is smallest). This can be overridden with attribute packed, as well as reassigning a pointer to a struct to misaligned address. Thus one can easily familiarize oneself with address misalignment exceptions.

While eg. Intel 8086 supported 16-bit reads at non-aligned addresses, one could still have the option of address generating exception when trying to access a word crossing segment boundaries (at offset 0xffff).

Aki Suihkonen
  • 19,144
  • 1
  • 36
  • 57
0

probably you needto change the default structure alignment. you can use either pragma in your code or compiler option. in case of gcc it is -fpack-struct[=n]

sergeyk555
  • 64
  • 3
0

Depending how you instantiate this:

struct foo{
    uint8_t thing1;
    uint16_t thing2;
};

may be aligned at even address but if compiler is not clever enough there will be no padding added between thing2 which entails thing2 to be at odd addres hence error. Either change members order or search compiler documentation for (probably some pragma preprocessor directives) that will allow compiler to help you align your data for you.

Artur
  • 7,038
  • 2
  • 25
  • 39