1

Does anyone know what the behaviour of std::string.assign(NULL) is? Assigning NULL (using operator) or constructing from NULL is undefined. Does the same apply for this function?

2 Answers 2

4

The standard says this in 21.4.6.3 paragraph 12:

Requires: s points to an array of at least traits::length(s) + 1 elements of charT.

In the character traits requirements Table 62 is says:

X::length(p) std::size_t yields: the smallest i such that X::eq(p[i],charT()) is true. linear

That implies that traits::length() will dereference s and, thus, s can't be a pointer to null. You get undefined behavior.

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

2 Comments

Could you tell me where you found that quote? I could only find something similar amongst the Boost documentation.
Disregard, I had to download a PDF... Had thought that the C++ guys would want people to see the standard, but clearly they don't - just Google that phrase!
1

It's undefined behavior to assign a C++ string from a NULL "C string", because a null pointer is not actually pointing to a C string at all. I could find no reference saying that std::string should check for NULL--you need to do it yourself.

1 Comment

Thanks. I'm aware that what this code attempts to do is 'morally' wrong, however technically there's no actual reason why memory location 0 can't contain a null-terminated string. This is why I wondered if 'modern' interpretations of this, featuring a properly defined nullptr, might actually catch the error rather than provoke the hardware/OS.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.