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:

using namespace std;

class Solution {
    int findContentChildren(vector<int>& g, vector<int>& s) {
        int i=0; int j=0; int n=g.size(); int m=s.size();
        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);
    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: