Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading