Is printing a null-pointer Undefined Behavior?

我的梦境 提交于 2019-12-04 01:28:30

问题


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 turns out that attempting to print a null pointer caused std::ios_base::badbit and std::ios_base::failbit to be set in its stream state which was the real cause for its being non-operational. Because of this, I am now curious if it really is Undefined Behaviour to (attempt) to print a null-pointer. So here are my questions:

  1. Is it Undefined Behaviour to print a null-pointer? If so, what is it about the stream inserter that would cause this? I'm pretty certain the inserter is smart enough to not dereference a null-pointer.

  2. I would also like to know why the inserter sets its error mask when encountering a null-pointer in this context (specifically badbit). Why doesn't it treat it like the termination of a string literal?

I don't have a Standard handy, and I only found one source thus far that unfortunately led to a dead link.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/23283772/is-printing-a-null-pointer-undefined-behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!