. Advertisement .
..3..
. Advertisement .
..4..
I am working on cpp, but I found the following warning message:
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_M_construct null not valid
Aborted (core dumped)
Is there any way to stabilize the issue “basic_string::_m_construct null not valid”? I read a lot of topics about this, but all of them were trying to install anything. Is this the correct way, or any recommendation for me? Please find the beginning command below:
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;
}
The cause:
There are two
return 0
; statements in your function. The function will return astd::string
but there is no constructors get aint
input. There is a constructor which can admita const char *
reference which 0 is changed implicitly. However, building astd::string
with a nullchar *
pointer is not a defined behavior. You don’t catch an exceptionstd::logic_error
which your implementation has selected in your code. Therefore, the error appears.Solution:
To solve this problem effectively, you need to returan an empty string:
Then the caller will check whether the return value has been set to empty or not:
This function returns a bool rather than a std::string, which would help you better.
You can return false or true if you change the return type to
bool
If you want to return
false
, then you should do so.It is not an error to return 0 from a Boolean Function. However, 0 will be automatically converted to false. But it is stylistically more important to clarify what you mean.