I'm afraid that you have to debug your 'wrong' code why it is failing. My experience these days is that if the output is wrong in higher optimization levels, it is likely a programming error (race condition, dangling pointers, wrong usage of memory, buffer overflow, ...).
What I recommend is that you carefully check compiler warnings, and that you increase the warning level to a 'pedantic' one. This should give you some hints.
The other approach is that you start reducing your application, to get a 'minimal failing example', to isolate the issue.
Last but not least, have a read at https://www.whyprogramsfail.com/
Good luck!
Erich