Is this code fragment OK or does it result in undefined behavior?
std::string s;
assert(strlen(s.c_str())==0);
If it isn't undefined behavior, will the above assertion pass?
The basic_string::c_str() is a builtin function in C++ which returns a pointer to an array that contains a null-terminated sequence of characters representing the current value of the basic_string object.
No. Since c_str returns a pointer p to a null-terminated array of characters, there must be some value i >= 0 such that p[i] == '\0' , and thus p cannot be null.
The c_str() method converts a string to an array of characters with a null character at the end. The function takes in no parameters and returns a pointer to this character array (also called a c-string).
c_str returns a "C string". And C strings are always terminated by a null character. This is C standard. Null terminating strings.
That is perfectly well defined and the assertion passes. The c_str() function will always return a valid zero terminated C string.
One would normally use empty() to test for an empty string.
Yes it will work (if you append ()
to c_str
to make it actually call the function) and the assertion will pass.
It's a compile error (if you have assertions enabled), since a const char *(std::string::*)()
, cannot be converted to const char *
implicitly.
(Tongue only halfway in cheek.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With