C++:(Leetcode) ==42==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000118

created at 08-07-2021 views: 12

When studying at Leetcode today, the code ran perfectly on the local compiler (VS Code+Gcc), but an error was reported when Leetcode was submitted:

cause of the error

==42==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000118 

It means that the heap buffer overflowed, but after careful inspection of the code, it seems that there is no problem. Besides, the test cases can be run when they are input into the local compiler, which is puzzling. code show as below:

#include<bits/stdc++.h>
using namespace std;

class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        sort(g.begin(),g.end());
        sort(s.begin(),s.end());
        int i=0; int j=0; int n=g.size(); int m=s.size();
        while(i<n&&j<m)
        {
            while(s[j]<g[i]&&j<m)
            {
                j++;
            }
            if(j<m)
            {
                i++;j++;
            }
        }
        return i;

    }
};


int main()
{
    Solution S;
    vector<int> g={10,9,8,7};
    vector<int> s={5,6,7,8};
    int a=S.findContentChildren(g,s);
    cout<<a<<endl;
    system("pause");
    return 0;
}

After checking for a long time, I finally realized that the reason for the error should be that the array was out of bounds. The problem should lie in this line:

 while( s[j]<g[i] && j<m )

The program is executed in the order from left to right, first judge s[j] <g[i], at this time j may have ≥ m, that is, it has exceeded the range of the array, just change these two orders, judge first Whether it’s out of bounds, change it to:

while( j<m && s[j]<g[i] )

Problem solved!

created at:08-07-2021
edited at: 08-07-2021: