You invoke the following overload of the std::string
constructor (overload 5):
basic_string( const CharT* s, const Allocator& alloc = Allocator());
And this is the explanation belonging to the constructor (emphasis mine):
Constructs the string with the contents initialized with a copy of the null-terminated character string pointed to by s. The length of the string is determined by the first null character. The behavior is undefined if [s, s + Traits::length(s)) is not a valid range (for example, if s is a null pointer).
Thus, you have undefined behavior at work. Referring back to your question, that outrules any further thoughts on "why it is happening", because UB can result in anything. You could wonder why it's specified as UB in the first place - this is because std::string
shall by design work with C-style, zero-terminated strings (char*
). However, NULL
is not one. The empty, zero-terminated C-style string is e.g. ""
.