On ulatra strange behavior remember gcc optimizations gan fuck with your code. See Flags: -Os <--- does for example remove empty while loops, which can be crusial for embedded devices.
In that case use something like -O0 if possible(because of flash size).