c++ - 运行时错误-UndefinedBehaviourSanitizer

标签 c++ runtime-error undefined-behavior cppcheck

  bool isPalindrome(int x) {
    
    if(x < 0){
        return false;
    }
    
    double log = log10(x);

  //below line is causing problem
  //I've tried this too  int totaldigits = floor(log) + 1;
 int totaldigits = floor( log +1 );
    
    int mask = pow(10,totaldigits-1);
    
    
    for(int i =0; i<(totaldigits / 2); i++){
        int atstart = x / mask;
        int atend = x % 10;
        
        if(atstart != atend){
            return false;
        }
       x %= mask;
        x /= 10;
        mask /= 100;
    }
    return true;
    
    
    
}
我在初始化总数位数的行上收到一个奇怪的Error.ON。
如果您有空闲时间来帮助我,我不会理解。
第10行:字符24:运行时错误:-inf超出类型为'int'的可表示值的范围(solution.cpp)
摘要:UndefinedBehaviorSanitizer:未定义行为prog_joined.cpp:19:24

最佳答案

if(x < 0)应该是if(x <= 0)
C++将log10(0)评估为-infinity,因此runtime error: -inf is outside the range of representable values of type 'int'如果输入为0,则写一个特例,例如:

if(x <= 0) {
    return !x;
}

关于c++ - 运行时错误-UndefinedBehaviourSanitizer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63521113/

相关文章:

c++ - 无法将 C++ 与 C 对象链接

c++ - Visual Studio,在数组声明中使用#define 常量时出现错误 : expected a ']' ,

c++ - 将函数地址转换为 64 位整数 : Undefined/Ill-behaved?

vb6 - Visual Basic 6 : Run-time error 424 (If Function)

C - 为什么我的数组被覆盖了?

c++ - C++ 中是否存在内存泄漏 "undefined behavior"类问题?

c++ - 具有不同返回类型的变体访问者

c++ - 将python代码转换为c++

使用构造函数填充 vector 的 C++ 奇怪行为

java - 损坏的双链表