Search code examples
c++runtime-errorundefined-behaviorcppcheck

Runtime error -UndefinedBehaviourSanitizer


  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;
    
    
    
}

I'm getting a strange Error.ON the line where I initialize totaldigits. I don't understand it IF you have free time help me with this;

Line 10: Char 24: runtime error: -inf is outside the range of representable values of type 'int' (solution.cpp) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:19:24


Solution

  • if(x < 0) should be if(x <= 0).

    C++ evaluates log10(0) as -infinity, hence

    runtime error: -inf is outside the range of representable values of type 'int'

    Write a special case for if the input is 0, for example:

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