How to fix ‘std::logic_error’ what(): basic_string::_M_construct null not valid error?

The problem is the two return 0; statements in your function. The function returns a std::string, which has no constructors that accept an int as input. But, it does have a constructor that accepts a const char * pointer, which 0 is implicitly convertible to. However, constructing a std::string with a null char * pointer is undefined behavior, and your implementation has chosen to throw a std::logic_error exception that you are not catching in your code.

In this case, I would simply return a blank string instead:

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;
}

The caller can then check if the return value is empty, if it wants to:

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

Which would be better served with a function that returns a bool instead of 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

Leave a Comment

error code: 523