Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling c_str of empty string

Tags:

c++

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?

like image 585
pic11 Avatar asked Nov 12 '11 08:11

pic11


People also ask

What is string c_str ()?

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.

Can c_str return null?

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.

What does c_str () mean in C++?

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).

Does c_str add null terminator?

c_str returns a "C string". And C strings are always terminated by a null character. This is C standard. Null terminating strings.


3 Answers

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.

like image 185
David Heffernan Avatar answered Sep 21 '22 00:09

David Heffernan


Yes it will work (if you append () to c_str to make it actually call the function) and the assertion will pass.

like image 41
Marcelo Cantos Avatar answered Sep 19 '22 00:09

Marcelo Cantos


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.)

like image 37
user541686 Avatar answered Sep 23 '22 00:09

user541686