简体   繁体   中英

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.

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.

You can fix that by rewriting your loop condition as:

i + 1 < nums.size()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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