Is trying to print a char with address 0x0 unpredictable behavior?

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

>Solution :

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.

Leave a Reply