Is printing a null-pointer Undefined Behavior?

后端 未结 2 932
旧巷少年郎
旧巷少年郎 2021-01-06 00:44

When studying the sample code for this question I had assumed it was Undefined Behaviour which was preventing subsequent uses of std::cout from printing. But it

相关标签:
2条回答
  • 2021-01-06 01:30

    gcc ostream.tcc line 319:

    template<typename _CharT, typename _Traits>
      basic_ostream<_CharT, _Traits>&
      operator<<(basic_ostream<_CharT, _Traits>& __out, const char* __s)
      {
        if (!__s)
    __out.setstate(ios_base::badbit);
    

    gcc is simply performing a check that the standard does not guarantee, which is fine because it's undefined anyway.

    0 讨论(0)
  • 2021-01-06 01:34

    basic_ostream's operator<<(basic_ostream<>&, const char*) function requires that the char* is non-null - it is designed to print the string the pointer points to. So it is undefined behavior to send a null char* to cout. (See C++11 27.7.3.6.4/3 "Character inserter function templates").

    However, basic_ostream's operator<<(basic_ostream<>&, const void*) function simply prints the value of the pointer, so a null pointer will work properly with that overload.

    0 讨论(0)
提交回复
热议问题