简体   繁体   English

空输入如何出现AddressSanitizer错误

[英]How come out the AddressSanitizer error for empty input

The following code compute the maximum gas between two adjacent elements. 以下代码计算两个相邻元素之间的最大气体。 The input vector is not sorted. 输入向量未排序。

class Solution {
public:
int maximumGap(vector<int>& nums) {
    int max = 0;
    sort(nums.begin(), nums.end());
    for(int i = 0; i < nums.size() -1; i++) {
        if(nums[i+1] > nums[i] + max) max = nums[i+1] - nums[i];
    }
    return max;
}
};

However, it generates the following error if input is empty (eg []) 但是,如果输入为空,则会产生以下错误(例如[])

AddressSanitizer:DEADLYSIGNAL
=================================================================
==29==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000004 (pc     0x00000040d54a bp 0x7ffe00e1e520 sp 0x7ffe00e1df50 T0)
==29==The signal is caused by a READ memory access.
==29==Hint: address points to the zero page.
#1 0x7fde1d3ab2e0 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x202e0)

AddressSanitizer can not provide additional info.
==29==ABORTING

The problem can be solved by including the following: 可以通过以下解决此问题:

if(nums.empty()) return 0;

Just wondering how does the error come about? 只想知道错误是如何产生的? I thought an empty input should also output 0 for the original code. 我认为空输入还应该为原始代码输出0。

nums.size() is of an unsigned type, so when it is zero, nums.size() - 1 is a huge positive number, and your loop will run. nums.size()是无符号类型,因此当它为零时, nums.size() - 1是一个巨大的正数,您的循环将运行。

You can fix that by rewriting your loop condition as: 您可以通过将循环条件重写为:

i + 1 < nums.size()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM