首页 > 解决方案 > 如何修复 'std::logic_error' what(): basic_string::_M_construct null not valid 错误?

问题描述

我正在尝试检查输入字符串是字母数字还是更大写或为空。如果输入字符串在上述出现故障的字符串中,我只想返回 false/0 否则可以与运行正常的程序的其余部分一起工作。我的程序块有问题:

std::string myfunc(std::string input){
    std::string b="";

    if (!input.size()) return 0;
    for (int i = 0; i < input.size(); i++){

        if ( input[i] < 'a' || input[i] > 'z'|| isalpha(input[i]) || isupper(input[i]) ) return 0;
    }
    b = input;
    //just copy the input string for now.
    return b;
}

我称这个函数为

int main(){
    std::string input="Somthing";
    std::cout << myfunc(input)<< std::endl;
    return  0;
}

得到以下错误?

terminate called after throwing an instance of 'std::logic_error'
  what():  basic_string::_M_construct null not valid
Aborted (core dumped)

没有这两种极端情况,该程序运行良好。我无法理解错误并找到解决方法?关于我做错了什么有什么建议吗?

标签: c++

解决方案


问题是您的函数中的两个return 0;语句。该函数返回 a std::string,它没有接受 aint作为输入的构造函数。但是,它确实有一个接受const char *指针的构造函数,0 可以隐式转换为。但是,std::string使用空char *指针构造 a 是未定义的行为,并且您的实现选择抛出std::logic_error您在代码中未捕获的异常。

在这种情况下,我会简单地返回一个空白字符串:

std::string myfunc(const std::string &input){
    if (input.empty()) return "";
    for (int i = 0; i < input.size(); ++i){
        char ch = input[i];
        if ( !((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) ) return "";
    }
    return input;
}

然后调用者可以检查返回值是否为空,如果它想要:

if (myfunc(input).empty())
    // error, do something
else
    // OK, do something else

bool使用返回 a而不是a 的函数会更好地服务std::string

bool isvalid(const std::string &input){
    if (input.empty()) return false;
    for (int i = 0; i < input.size(); ++i){
        char ch = input[i];
        if ( !((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) ) return false;
    }
    return true;
}

// if you still needed this function for something...
std::string myfunc(const std::string &input){
    if (!isvalid(input)) return "";
    return input;
}

if (!isvalid(input))
    // error, do something
else
    // OK, do something else

推荐阅读