Leetcode报错:[AddressSanitizer: heap-buffer-overflow on address xxxx at pc xxxxx bp xxxx]

    背景:win32+devcpp 5.11

    问题:下述代码在本地devcpp运行无误,leetcode报错地址越界

class Solution {
public:
    vector num;
    vector::iterator it;
    vector > minimumAbsDifference(vector& arr) {
		vector > mini;
		vector::iterator it;
		vector >::iterator iter;
        sort(arr.begin(),arr.end());//步骤一排序
		int t=abs(*(arr.end())-*arr.begin());//t记录最小差值 
        
		for(it=arr.begin()+1;itk){
				swap(t,k);
			}
		}
		
		for(it=arr.begin()+1;it vec;
			if(t==*(it)-*(it-1)){//找到了元素对 
				// cout<<*(it-1)<<" "<<*it<

仔细排查发现第十行的int t=*arr.end()-*arr.begin();出错,arr.end()返回一个指向最后一个元素后面一位的迭代器,再用*使用该元素,元素不存在,访问越界了。

将其改为:int t=*(arr.end()-1)-*arr.begin();后通过LeetCode检测。

深入一步:为啥devcpp中没有检测出这个bug?

你可能感兴趣的:(PTA,蓝桥杯,leetocde,洛谷)