Search code examples
c++while-loopbuffer-overflow

Address Sanitizer Heap buffer Overflow


I was trying to solve this problem on leet code it works fine on my vs code and gcc compiler but i'm getting this Runtime error: Address sanitizer Heap buffer Overflow error message with a long list of address or something on the website. Help me fix it. Here's the code

class Solution
{
public:
    char nextGreatestLetter(vector<char> v, char a)
    {
        int l=v.size()-1;
        if (v[l] < a)
        {
            return v[0];
        }
        int i = 0;
        while (v[i] <= a)
        {
            i++;
        }
        return v[i];
    }
};

p.s the array is sorted in ascending order


Solution

  • This code snippet has a lot of problems:

    • The while loop isn't guaranteed to terminate. If the last character of v is == a, then the first v[l] < a test will be false, but v[i] <= a might be true all the way through the array (it looks like v is meant to be pre-sorted into ascending order), which will have you eventually accessing v[i] for a value of i >= v.size(). That is an illegal/undefined array access and might be the source of the error message you report, if the test platform had strict bounds-checking enabled.

    • The logic of returning v[0] if a is greater than any character in v (again, inferring from the loop that v is supposed to be pre-sorted into ascending order) also seems flawed. Why not return the value of a instead? The caller can easily see that if the return value was <= a, then there clearly was no element of v greater than a.

    • It's almost certainly worth your time to handle cases where the passed-in v array is empty (v.size() == 0) or not actually pre-sorted, i.e. by caching n = v.size() and changing the loop condition to while (i < n && v[i] <= a). Don't let fragile functions creep into your codebase!