Source of the problem
In the cattle network discussion group, someone raised the question code:
char *p NULL;cout << p;******intNULL;cout << q;
The above code in Windows using VS, an error will not be an error ~ but under Linux does not error ~
Guess
- The character pointer is a direct print pointer to the value (string) that accesses the contents of the null pointer;
- int pointer, output is the value of the print pointer (null=0), so there is no error.
- and Linux below will not error, it must be different compiler processing is not the same ~
Verify
- The program runs on the ubuntu14.04, using g++
- And did not go to Windows under verification, but saw the results of others running similar programs
The procedure is as follows:
#include <iostream>#include <cstring>using namespace STD;intMain () {CharA[] ="hello,world!";cout<<"A ' s address is"<< &a << Endl;Char*p = A;cout<<"The P ' s value is:"<< (void*) (p) << Endl;cout<<"The content is:"<< p << Endl; p = NULL;cout<<"The P ' s value is:"<< (void*) (p) << Endl;cout<<"The content is:"<< p << Endl;if(cout. Bad ()) {cout. Clear ();cout<< Endl;cout<<"If @p __SB is NULL, the stream would set failbit in it error state."<< Endl; }int*q = NULL;cout<<"Q ' s value is"<< Q << Endl;cout<<"The content is"<< *q << Endl;return 0;}
Compile run:
[email protected]:~/code/C/pointer$ ./a.out a‘s address is 0xbf897d7fthe p‘s value is: 0xbf897d7fthe content is: hello,world!the p‘s value is: 0the content is: If @p __sb is NULL, the stream will set failbit in its error state.q‘s value is 0段错误 (核心已转储)
Conclusion
- As you guessed, Cout's << encountered a different interpretation of the output of char * and int * when overloaded.
- g++ when encountering the null character pointer, will be in the error state, set as Fallbit, which can be found by viewing the source code:
/**
- @brief extracting from another streambuf.
- @param __SB A pointer to a STREAMBUF
*
- This function behaves like one of the basic arithmetic extractors,
- In so it also constructs a Sentry object and has the same error
- Handling behavior.
*
* If @p __SB is NULL, the stream would set failbit in it error state.
*
- Characters is extracted from @p __sb and inserted into @c *this
- Until one of the following occurs:
*
-
- The input stream reaches End-of-file,
-
- Insertion into the output sequence fails
- Character that would has been inserted is not extracted), or
-
- An exception occurs and getting a character from @p __SB, which
- Sets Failbit in the error state
*
- If the function inserts no characters, Failbit is set.
*/
__ostream_type&
operator<< (__streambuf_type* __SB);
Interpretation of pointers such as cout character pointers and int