Why does std::cout output disappear completely after NULL is sent to it

Solution 1:

const char* some_string = a_function_that_returns_null();

Do you mean that it literally returns a null pointer?

[2003: 27.6.2.5.4]:

template<class traits>
basic_ostream<char,traits>& operator<<(basic_ostream<char,traits>& out, const char* s);

3. Requires: s is non-null.

Then streaming some_string is Undefined Behaviour; you cannot dereference a pointer to get a string — even an empty one — if the pointer is not valid.


This doesn't happen all the time - a co-worker with the same code gets all the expected output

UB leads to unreliable symptoms. That you don't always get a crash can be slightly surprising because most modern OSs make a point of always SIGSEGVing when you try to dereference a null pointer.

However, from a C++ point of view, anything can happen; in your particular case, your standard library implementation may well be checking for a null pointer and setting an error flag on the stream instead of attempting to dereference the pointer. That is its prerogative.

(It's also probably why your subsequent stream operations are failing: attempting to write to a stream does nothing when there's an error flag set.)

For example, the libstdc++ that ships with GCC 4.6.0, despite naming s != 0 as a precondition, does do this:

00325       if (!__s)
00326     __out.setstate(ios_base::badbit);
00327       else

However, you must not rely on this behaviour; it could change at any time!


So, simply don't do this. Stream a valid, but empty, string if you really must.

And what's wrong with std::string?

Solution 2:

I'm fairly sure that cout << (char*)NULL has undefined behavior. I'm afraid that "Don't do that" is the best advice I can offer.