標籤:指標
問題來源
在牛客網的討論群裡,有人提出了這樣的問題代碼:
char *p = NULL;cout << p;******int *q = NULL;cout << q;
上述代碼在windows下面使用vs,一個會報錯一個不會報錯~ 但是在linux下面並不會報錯~
猜想
- 字元指標是直接列印指標指向的值(字串),訪問了null 指標的內容;
- int指標,輸出是列印指標的值(null=0),所以不會報錯.
- 而linux下面不會報錯,那肯定是不同編譯器的處理不一樣了~
驗證
- 程式在ubuntu14.04上跑的,使用g++
- 並沒有去windows下面驗證,但看過別人運行類似程式的結果
程式如下:
#include<iostream>#include<cstring>using namespace std;int main(){ char a[] = "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 will set failbit in its error state." << endl; } int *q = NULL; cout <<"q‘s value is " << q << endl; cout << "the content is " << *q << endl; return 0;}
編譯運行:
[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段錯誤 (核心已轉儲)
結論
- 如猜測的一樣, cout 的<< 在重載時,遇到char * 和int *的輸出解釋是不一樣的
- g++在遇到Null 字元指標時,會在錯誤狀態中,置為fallbit,這個通過查看源碼是可以找到的:
/**
- @brief Extracting from another streambuf.
- @param __sb A pointer to a streambuf
*
- This function behaves like one of the basic arithmetic extractors,
- in that it also constructs a sentry object and has the same error
- handling behavior.
*
* If @p __sb is NULL, the stream will set failbit in its error state.
*
- Characters are 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 (in this case, the
- character that would have been inserted is not extracted), or
-
- an exception occurs while 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);
cout 字元指標和int等指標的解釋