Reputation: 31
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?
Upvotes: 0
Views: 255
Reputation: 3432
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.
Upvotes: 1