Ruslan Neshta
Ruslan Neshta

Reputation: 23

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?

Upvotes: 2

Views: 1706

Answers (3)

Kargath
Kargath

Reputation: 528

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

Upvotes: 1

supercat
supercat

Reputation: 81159

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.

Upvotes: 0

Ben Voigt
Ben Voigt

Reputation: 283634

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.

Upvotes: 4

Related Questions