On 15/07/2023 12:43, James R T via Gcc-help wrote:
Hi folks, 2. Regardless of whether this is UB or not, is it possible for GCC to also output a warning in `-O0` as in `-O2`? If the behavior changes across different optimization levels, it seems that it's worth a warning or two. It can be a different warning instead of `-Wdangling-pointer` since looking at the produced assembly code, GCC seems to simply optimize out the whole conditional assignment block in `-O2`. If it is UB, I understand that it is impossible to catch all UB, but I am just checking on whether it is possible to catch this specific one from GCC's perspective. Just FYI, I have also tried using `-fsanitize=address` and `-fsanitize=undefined` and it seems that AddressSanitizer would throw a `stack-use-after-scope` error in GCC if `-fsanitize=address` is specified for both `-O0` and `-O2`, but not in Clang. `-fsanitize=undefined` does not seem to be able to detect anything.
I think you've had solid answers to your other points already, so you can see why it is UB.
When you use the -O flags, you are not just enabling a selection of optimisation passes - you are also changing the code analysis passes. With -O0, relatively little analysis is done. This means that many warnings are not active at -O0. So it is quite normal for warnings like this to require -O1 or above to work, and some may need -O2 to work fully (I don't have details off-hand - I'm a long-term gcc user, not a gcc developer).
Personally, I've never had any use for -O0 - I use -O2 usually and -O1 at a minimum, even for early checking of code, precisely because it allows far better static warnings.