optimiser emits ud2 (invalid-opcode trap) for a fully defined C loop at -Ot and

Started by KEL26, August 30, 2026, 11:09:48 PM

Previous topic - Next topic

KEL26

=====================================

Please, to all helpful users, read all of my text in each section,  before 'helping' me out - I explained the problem as clear as I could, with code and words - please explain using sentences rather than just pure code - the penny will then, hopefully, drop.
I am a professional programmer and I have been debugging C-language with (almost) 'ease' for years.  How to detect the bug, this code, has been shown in my zipped folder, that I attached for Dear Pelle and for all who wish to see, I appreciate explanations with any code you post to help me and others.

=====================================

Robert, thank you. Your printf line gives the clearest picture of the fault so far. Under /O2 it prints all two hundred stored values cycling 0 to 43, and it does so in both of your optimised runs. That is the bug in full: 300 modulo 256 is 44.

The change to the checksum line does not alter that, and your own output shows it. The printed array is identical, and wrong, in both /O2 runs. Only the checksum differs, and the reason is that

sum += (*data)++;

never reads the element at index i. It reads the first element two hundred times, adding the old value and incrementing it, so from zero it sums 0+1+...+199 = 19900 whatever the other 199 bytes contain. I checked this by filling the array with 0xFF in every byte but the first, which was set to zero: that loop still prints 19900.

So the fix changed the measurement rather than the data. The array your program prints is the real result. It is wrong under /O2 and right without it, which is exactly what Timo's element check found and what has now gone to Pelle. Your run makes it three machines.