将指向NULL的char型指针变量赋值给string对象将会导致段错误。如下示例代码
#include<cstdio>
#include<iostream>
#include<string>
#include<algorithm>
#include <sys/vfs.h>
#include <string>
using namespace std;
int main()
{
string str1;
char *p = NULL;
const char *q = "";
//str1 = p; //这句代码会报Segmentation fault (core dumped),因未指向任何内存空间
printf("p addr:%p\n", p);
printf("q addr:%p\n", q);
str1 = q; //正常。指向了一个常量字符空间,只是这部分空间未存放字符串
cout<<"str1 size is:"<<str1.size()<<endl;
}
测试代码执行结果: