首页 > 解决方案 > C++ 运行时错误:添加无符号偏移量?

问题描述

我写了以下内容来检查文本是否是回文,我在 leetcode 上运行它,我得到了错误:

class Solution {
public:
    bool isPalindrome(string s) {
        int l=0,r=s.length()-1;
        while(l<r)
        {
            while (!isalpha(s[r]))
            {
                --r;
            }
            while (!isalpha(s[l]))
            {
                ++l;
            }
            if (tolower(s[r])!=tolower(s[l]))
                return false;
            --r;
            ++l;
        }
        return true;
    }
};

第 1061 行:字符 9:运行时错误:将无符号偏移量添加到 0x7ffc7cc10880 溢出到 0x7ffc7cc1087f (basic_string.h) 摘要:UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/ ../../../../include/c++/9/bits/basic_string.h:1070:9

我的代码有什么问题?

标签: c++stringc++11

解决方案


你在这里越界了:

while (!isalpha(s[r]))

和这里

while (!isalpha(s[l]))

r可以变成负数,l也可以变成>= s.length()

您应该添加一些检查,例如

while (l < r && !isalpha(s[r]))

while (l < r && !isalpha(s[l]))

此行中的相同问题

if (tolower(s[r])!=tolower(s[l]))

这应该是

if (l < r && tolower(s[r])!=tolower(s[l]))

不同的方法 (C++20)

s另一种方法是从with中删除所有非字母字符

std::erase_if(s, [](char c) { return !isalpha(c); });

并删除内部的while循环。


推荐阅读