Yesterday I encountered and fixed a bug in some AVR code of mine. It was a pretty stupid bug: I neglected to check the number of bytes I was telling
memset() to operate on. The line of code was as follows:
memset(&foo[foo_len], 0x00, foo_max - foo_len);
Fairly straightforward - I wanted to fill the remaining space in an array with zeros. Except, a mistake in a preceding line of code made
foo_len in certain circumstances have a value one larger than
foo_max. Whoops, my calculated size value is negative and just got wrapped around into a large positive integer, so I just asked
memset() to write to 65,535 bytes of memory!
Unsurprisingly, this did not have positive effects.
The AVR microcontroller crashed and reset. What I am curious to learn is by what mechanism the reset occurred.
If I had to make an educated guess, I would say that writing zeros to RAM proceeded unimpeded all the way to the end of the address space (2K RAM on the part I'm using, so address 0x08FF according to the datasheet) and then wrapped around to the beginning, where it trampled on the CPU registers, which is what caused the reset. Perhaps because the execution pointer got written to zero, so effectively jumping to the start of program memory?
I would be interested to hear whether my guess is correct.