Function return not catching the undefined behavior

I’m not sure if this is undefined behavior or not and it may be discussed before or not. I was testing some random code snippets to try “-fsanitize=undefined” but in this example:

#include

char func(int a, int b) {
int sum = a+b;
return sum ;
}

int main() {
int n;
char s = func(100,100);
int t = func(100,100);
std::cout << “hello” << s << t;
return 0;

}

I was expecting some kind of undefined behavior here because of some overflowing the char return type with integer return type. But “-fsanitize=undefined” is not able to catch this . And I got the output this : hello�-56

Kinda weird for me .

And if I’m wrong or misunderstand something then please let me know.

I’m not sure that is undefined behavior, but it is caught by -fsanitize=integer

This is implementation-defined, not undefined. C99 6.3.1.3p3:

Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

Jess

Right, exactly. To Phy: The math is being done as ‘int’, where there IS no overflow. The narrowing conversion is implementation defined, so that isn’t UB.

Note that EVEN IF you change all of the ‘int’ to ‘char’ in ‘func’, the math ‘a+b’ is still done as ‘integer’ by rule, then narrowed, so you won’t get the overflow sanitizer here unless your inputs overflow the ‘int’ type.