Search code examples
cmicrocontrolleratmega

outcome depends on order of variable initialization?


I am experimenting with SPI on an ATmega16a and therefore initialize the following variables (outside of any method) in C:

uint8_t refreshCounter = 0;
uint8_t sendBuffer[32] = {};
volatile uint8_t doSend = FALSE;
char lineBuffer[20] = {};

With these lines everything works as expected, but when I switch the last two lines, my program stops working (at least the remote SPI module does not answer):

uint8_t refreshCounter = 0;
uint8_t sendBuffer[32] = {};
char lineBuffer[20] = {}; 
volatile uint8_t doSend = FALSE;

What is wrong with these definitions? Why is the order important?

doSend is volatile because it is used within an interrupt handler. All other variables are only accessed within the endless main-loop. Tell me, if you need more code.


Solution

  • Turning @WhozCraig's comment into an answer: Yes, I wrote 21 bytes into my lineBuffer with the following line

    sprintf(lineBuffer, "%20c", ' ');
    

    because sprintf appends a trailing null space. My fault.

    Thank you @WhozCraig!