为什么我仅在leetcode中遇到此运行时错误,但编辑器却没有,效果很好
我的代码:
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;
}
};
错误:
行1061:char 9:运行时错误:添加无符号偏移到0x7fff3d1ffc60溢出到0x7fff3d1ffc5f(basic_string.h) 摘要:undefinedbehaviorsanitizer:undefined-behavior/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../../../../../../ include/c+++++++++++++++++++++++++++++++++++++++++++++++++sctring.hbasic_string.h.h :1070:9
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您从零开始,然后尝试获取
s [rightptr -1]
,即s [-1]
- of Out array bunds访问。数组正在启动,第一个数组char位于偏移0x7fff3d1ffc60上,在offset 0x7fff3d1ffc5f上读取char-错误在说什么。You start with zeros and attempt to get
s[rightptr - 1]
that iss[-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.首先通过循环的时间,
rightptr
设置为零,您评估s [rightptr -1]
。这不会很好地结束:-)我建议您将第二个
如果
语句更改为从那里开始调试。可能还有其他问题,但至少可以解决直接问题。
The first time through your loop,
rightptr
is set to zero and you evaluates[rightptr - 1]
. That's not going to end well :-)I suggest you change your second
if
statement toand start debugging from there. There may be other problems but at least that'll solve the immediate one.