简体   繁体   中英

MSVC C/C++ compiler undefined behavior warning

I've compiled simple UB code without any warnings or errors using Visual Studio 2019:

int main()
{
    int i = 10;
    i = i++ + ++i;
    return i;
}

I've turned on EnableAllWarnings(/Wall) and treat warnings as errors(/WX) flags. It compiled into:

mov         eax,17h  
ret  

Because compiler generated this code, I'm sure that he detected UB. Why doesn't MSVC generates any warning about UB?

I've checked that Clang and GCC gives warnings for this example. Do they generate warnings for any possible UB? If so, why MSVC doesn't?

Clang and GCC gives warnings for this example. Do they generate warnings for any possible UB?

No. Many things are defined as "undefined behavior" instead of requiring a diagnostic, exactly because they are extremely difficult (or even theoretically proven to be impossible) to detect with 100% accuracy.

Suppose the code had been *p = (*q)++ + ++(*r); In that case, a compiler would generally have no way of knowing which if any combinations of pointers would be identifying the same objects. While it would be simple to make a compiler issue a diagnostic in simple code snippets like yours, the likelihood of anyone accidentally writing such code would be rather remote compared to the likelihood of failing to separate operations on pointers that happen to identify the same objects. A compiler isn't going to issue a diagnostic for a construct unless the author or maintainer writes code to do so. While some compilers' writers spend a lot of effort including such diagnostics, many others judge that any time and effort they could have to spend including such diagnostics would be better spent on supporting other, more useful, features.

in clang you can use like that:

clang++ -fsanitize=undefined test.cpp

When the program runs, it will report errors like that

visual studio already supports address_sanitizer. It seems that UndefinedBehaviorSanitizer will have to wait a while

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM