1
static bool mycompare(const string &a, const string &b)
{
    return a.size() <= b.size();
}

int main() 
{
vector<string> words;
sort(words.begin(),words.end(),mycompare);

}

I am getting "Error : Address sanitizer : heap buffer overflow on address.". But if change comparator function operator from "<=" to "<" then it compiles fine. I am not able to understand this error if <= operator is used. Input is ["ksqvsyq","ks","kss","czvh","zczpzvdhx","zczpzvh","zczpzvhx","zcpzvh","zczvh","gr","grukmj","ksqvsq","gruj","kssq","ksqsq","grukkmj","grukj","zczpzfvdhx","gru"]

enter image description here

sachin
  • 97
  • 12
  • The `std::sort` is asking you if `a` should be placed before `b` in the sort. What happens if `a == b`? You answered `true` that `a` should be placed before `b`, and you answered `true` that `b` should be placed before `a`. You can't have `a < b` and `b < a` at the same time, thus the error. That's why the `<=` should be changed to `<`, since an equality comparison will break the strict-weak-order. – PaulMcKenzie Jul 25 '21 at 06:32
  • @PaulMcKenzie Thank you sir for your answer. I have one question. Why do std::sort need to compare both a < b and b < a ? standard sorting algorithms compare one way , not both way. – sachin Jul 26 '21 at 07:31
  • @sachin -- Comparison of a < b and b < a is one method of determining if your sort comparison is valid. That is exactly how the Visual C++ debug runtime determines if the sort criteria is valid. The debug routines first give you "a, b" -- you return `true`. Then to check, the sort routine then gives you "b, a" -- you return `true`. That is a contradiction -- you told `std::sort` that a comes before b, and that b comes before a. If you wrote your program and ran it under Visual C++, you will be greeted with a big `assert()` box saying that your comparison is invalid. – PaulMcKenzie Jul 26 '21 at 15:23
  • And note, this is the *debug* runtime. The release version does not do this check, and simply trusts that your sort comparison is valid. – PaulMcKenzie Jul 26 '21 at 15:25

0 Answers0