0

I was trying to solve this problem : Third Maximum Number

but I was getting this error

Line 4: Char 37: runtime error: signed integer overflow: -9223372036854775808 - 10 cannot be represented in type 'long long' (solution.cpp) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:13:37

this my code

class Solution {
public:
    int thirdMax(vector<int>& nums) {
        long long int mx = LLONG_MIN-10;
        long long int second_mx = LLONG_MIN-10;
        long long int  third_mx = LLONG_MIN-10;
        for(int i=0; i<nums.size(); i++){
            if(nums[i] > mx){
                mx = nums[i];
            }
        }
        
        for(int i=0; i<nums.size(); i++){
            if(nums[i] != mx){
                if(nums[i] > second_mx){
                    second_mx = nums[i];
                }
            }
        }
        
        for(int i=0; i<nums.size(); i++){
            if(nums[i] != mx && nums[i] != second_mx){
                if(nums[i] > third_mx){
                    third_mx = nums[i];
                }
            }
        }
        if(third_mx == LLONG_MIN){
            return mx;
        }
        return third_mx;
    }
};

can someone please tell me what does this error really means?

IMSoP
  • 89,526
  • 13
  • 117
  • 169
Ayushaps1
  • 31
  • 3
  • What compiler flags are you using? You should be getting some dire compiler warnings about `return mx` as your method's return type is `int` but `mx` is `long long int` (`int` is typically `int32_t` while `long long int` is typically `int64_t`). And if you are getting those warnings, why didn't you fix them before continuing? – Dai Jun 13 '21 at 11:27
  • Just what it says. The result of `LLONG_MIN-10` cannot be stored in a `long long` (aka `long long int`). Think about it. `LLONG_MIN` is the minimum value (negative value furthest from zero since `long long` is a `signed` type) that can be stored in a `long long`. `LLONG_MIN-10` is less than that minimum value, so cannot be stored in a `long long`. – Peter Jun 13 '21 at 12:25

1 Answers1

1

The line

long long int mx = LLONG_MIN-10;

takes LLONG_MIN, the minimal value a long long int could store, and subtracts 10. Obviously, this value can not be stored in long long anymore, so this causes an overflow, which results in undefined behavior.

You program was run with the Undefined Behavior Sanitizer, which detected this and gave you the error.

He3lixxx
  • 3,263
  • 1
  • 12
  • 31