问题来源
在牛客网的讨论群里,有人提出了这样的问题代码:
char *p = NULL;
cout << p;
******
int *q = NULL;
cout << q;
上述代码在windows下面使用vs,一个会报错一个不会报错~ 但是在linux下面并不会报错~
猜想
- 字符指针是直接打印指针指向的值(字符串),访问了空指针的内容;
- 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 0xbf897d7f
the p‘s value is: 0xbf897d7f
the content is: hello,world!
the p‘s value is: 0
the 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++在遇到空字符指针时,会在错误状态中,置为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);
时间: 2024-10-15 03:21:30