如何修复C++运行时错误:无符号偏移相加

oxiaedzo  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(205)
  1. string removeDuplicates(string s) {
  2. for(int i = 0; i<s.length(); i++){
  3. int count = 0;
  4. while (s[i-count]==s[i+1+count])
  5. count += 1;
  6. i -= count;
  7. s.erase(i+1,2*count);
  8. cout<<s<<endl;
  9. }
  10. return s;
  11. }

您将得到一个由小写英语字母组成的字符串s。重复删除包括选择两个相邻且相等的字母并删除它们。
我们在s上重复删除,直到我们不能再删除为止。
删除所有重复的字符串后返回最后一个字符串。可以证明答案是唯一的。
这是leetcode问题1047。我的代码在vscode中运行,但是当我提交这个时,我得到了错误。如果您知道错误,请提供帮助。

  1. Line 1065: Char 9: runtime error: addition of unsigned offset to 0x7ffd301f5600 overflowed to 0x7ffd301f55ff (basic_string.h)
  2. SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/basic_string.h:1074:9
s5a0g9ez

s5a0g9ez1#

考虑这个字符串"aa"发生了什么。
首先icount等于零,所以s[i-count]==s[i+1+count]为真,所以执行count += 1;
现在i等于0,count等于1,再次检查s[i-count]==s[i+1+count],但这一次i-count等于-1,所以您检查s[-1],这是非法的,并导致您看到的错误消息。
也许s[i-count]s[i+count]的一个错字,但即使有了这个改变,我也不认为你的程序是正确的。
你需要做的是更仔细地考虑你写的代码。每次你写X[Y]时,你都必须考虑Y对于X来说是太大还是太小。仅仅在大多数时候是正确的是不够的,它必须在所有的时候都是正确的。

相关问题