-3

My Code :

class Solution {
    public:
    string longestPalindrome(string s) {
    string tmp ="", res = "",emp = "";
    int leftptr =0,rightptr=0;
     while(rightptr < s.size())
    {
       if(leftptr == rightptr || s[rightptr] != s[leftptr])
       {
           if(s[rightptr] ==  s[rightptr - 1] && s.size()>0)
           {
               if(emp.size() == 0)
               {
                   emp.push_back(s[rightptr - 1]);
                   emp.push_back(s[rightptr]);
               }
               else
               {
                   emp.push_back(s[rightptr]);
               }
           }
           tmp.push_back(s[rightptr++]);
       }
       else if(s[leftptr] == s[rightptr])
       {
           tmp.push_back(s[rightptr]);
           if(res.size() < tmp.size()){
            res = "";
            res = tmp;
            tmp = "";
           }
           tmp.push_back(s[++leftptr]);
       }
   }
   if(res.size() > emp.size())
        return res;
   else
        return emp;   
    }
    };

error :

Line 1061: Char 9: runtime error: addition of unsigned offset to 0x7fff3d1ffc60 overflowed to 0x7fff3d1ffc5f (basic_string.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/basic_string.h:1070:9

  • And the lesson is that *it works good* does not mean *my program has no bugs*. This is a **very** important lesson to learn as a C++ programmer. – john Jun 27 '22 at 07:42
  • @john: "This is a very important lesson to learn as ***any*** sort of programmer." There, fixed that for you :-) – paxdiablo Jun 27 '22 at 07:43

2 Answers2

1

You start with zeros and attempt to get s[rightptr - 1] that is s[-1] - the out of array bounds access. The array is starting, the first array char is located at the offset 0x7fff3d1ffc60, reading a char at offset 0x7fff3d1ffc5f - what the error is saying.

273K
  • 29,503
  • 10
  • 41
  • 64
0

The first time through your loop, rightptr is set to zero and you evaluate s[rightptr - 1]. That's not going to end well :-)

I suggest you change your second if statement to

if((rightptr > 0) && (s[rightptr] == s[rightptr - 1]) && (s.size() > 0))

and start debugging from there. There may be other problems but at least that'll solve the immediate one.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953