-1

I would like to hear the theoretical explanation of what is happening here

#include <iostream>

int main(){

 int ooh=0x0;
 char *cc=0x0;

  std::cout<<"hello!"<<cc<<"still"<<ooh<<"\n";

}

When running this we got

hello!

and the program finishes. I suppose it is because we are trying to print an address 0x0 I know it is wrong, but I would like to hear why is this wrong and what is happening under wraps

KansaiRobot
  • 7,564
  • 11
  • 71
  • 150
  • 1) What makes you think that is a valid address that your program has access to? Commonly it won't be. 2) What do you think is there, you haven't put anything there? Why do you think a null terminated c- style string is there? _Expect undefined behavior._ – Avi Berger Apr 27 '23 at 05:07
  • @237K The duplicate doesn't answer the question of whether/why it is UB. – user17732522 Apr 27 '23 at 05:08
  • @AviBerger Thanks for the comment. I know it is *not* a valid address. In fact I am reviewing someone else's code and this happens. So I want to explain it with more than "this is something you should not do" – KansaiRobot Apr 27 '23 at 05:09
  • @user17732522 Exactly. Unfortunately the question was closed, and the duplicates do not address the question. Hope someone can explain to me it in the comments – KansaiRobot Apr 27 '23 at 05:10
  • @user17732522 You haven't given me a chance to extend the list with dupes: https://stackoverflow.com/questions/23283772/is-printing-a-null-pointer-undefined-behavior and https://stackoverflow.com/questions/7019454/why-does-stdcout-output-disappear-completely-after-null-is-sent-to-it – 273K Apr 27 '23 at 05:11
  • 1
    `cc` is a *null pointer* of type `char*`. You cannot dereference such pointer or pass it to the `<<` operator to be printed. What happens when you do it anyway is *undefined*. It is undefined because the standard says so. It makes little sense to ask "what is happening under wraps" when the behaviour is undefined, because literally anything may happen. If you want to know what *your compiler* does with it *on your machine today*, look at the disassembly, and be aware that tomorrow it may be something completely different. – n. m. could be an AI Apr 27 '23 at 05:17

1 Answers1

3

It has undefined behavior, because the specification of the operator<< overload for std::basic_ostream which is chosen here for <<cc has a precondition that the passed pointer is not a null pointer value and is instead pointing to a null-terminated byte string.

See e.g. https://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt2:

The behavior is undefined if s is a null pointer.

of if you prefer to look in the standard draft itself, see [ostream.inserters.character]/3.

The line char *cc=0x0; initializes cc to a null pointer value.

user17732522
  • 53,019
  • 2
  • 56
  • 105