3

I have read several topics here and on other resources and did not found exact answer. The answer seems to be never. Please confirm.


Stop. Not never. As noted in Why can you assign nullptr to std::string?:

std::string str {nullptr}; // Undefined behavior 

So if this will not throw (depends on implementation), c_str() could return (char_t*)nullptr.

I believe there are no other ways to get nullptr from c_str(). But must ask StackOverflow community to be sure. Thanks for attention.

7
  • 1
    No, c_str() will always return a null-terminated C-style string, assuming no prior undefined behaviour. Commented Jul 23, 2017 at 19:23
  • Passing nullptr to string::string will just make the string try to interpret (char*)nullptr as a pointer to a c-string. It will still copy the mis-pointed c-string to its managed storage Commented Jul 23, 2017 at 19:23
  • 1
    @NeilButterworth: "null-terminated C-style string" is a bit redundant, since a C-style string is by definition a null-terminated array of characters. You cannot have a "non-null-terminated C-style string", if you will. That wouldn't be a C-style string. Commented Jul 23, 2017 at 19:25
  • 1
    @Kerrek In my experience a little redundancy is never a bad thing when it comes to explanations. Commented Jul 23, 2017 at 19:26
  • 2
    std::string str {nullptr}; // Undefined behavior as you note, this is undefined behavior, so all bets are off. You can't use something that happens after you invoke undefined behavior as a counter-example. Commented Jul 23, 2017 at 20:05

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

What if nullptr can be dereferenced on your platform and returns 0?
@Yakk: Every p[k] must point to an object for 0 <= k <= i, and the address of an object is never a null pointer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.