简体   繁体   English

C ++:字符串= NULL给出SEGFAULT 11?

[英]C++: string = NULL gives SEGFAULT 11?

I modified my project today to allow it save files in different folders, and I found my program crashed when startup: 我今天修改了项目,使其可以将文件保存在不同的文件夹中,发现启动时程序崩溃:

Segmentation fault: 11

Because I introduced so many changes before testing my program, I started comment out all the functions I added, but no help. 因为我在测试程序之前引入了许多更改,所以我开始注释掉我添加的所有功能,但是没有帮助。 I even put 我什至放

cout << "hello world" << endl;
return 0;

as the first two lines in int main() , it still crashed without showing anything. 作为int main()的前两行,它仍然崩溃而未显示任何内容。

Finally, it took me one hour to figure out the error. 最终,我花了一个小时才弄清错误。 The modification includes declaring a global variable 修改包括声明全局变量

string foldername = NULL;

The line above seems innocence, it just declaring a global variable. 上面的行似乎是纯真的,它只是声明了一个全局变量。

Then I tried a simple program: 然后我尝试了一个简单的程序:

#include <string>

std::string a = NULL;

int main(){
    return 0;
}

and it also crashed at startup. 并且在启动时也崩溃了。

Why declaring a string global variable as NULL make the program silently crashed without any info? 为什么将字符串全局变量声明为NULL会使程序无提示地静默崩溃?

The std::string - as opposite to inherited from C char* strings - always holds a valid string. 与从C char*字符串继承的相反, std::string始终包含有效字符串。 It may be empty, but it cannot be NULL. 它可以为空,但不能为NULL。 If you try to initialise std::string with NULL it will try blindly to copy C-like string from NULL address, which is undefined behaviour. 如果尝试使用NULL初始化std::string ,它将盲目尝试从NULL地址复制类似C的字符串,这是未定义的行为。

Just use 只需使用

std::string a;

and then a will be initialised empty string. 然后a将被初始化空字符串。

NULL is assigned only to pointer types and that too in C. The C++ way is std::nullptr_t or nullptr . NULL仅分配给指针类型,C中也分配给指针类型。C++方式为std::nullptr_tnullptr Either declare pointer to a string like 要么声明指向类似字符串的指针

std::string * a = nullptr;

or leave it to the string constructor 或将其留给字符串构造函数

std::string a = "";    // equivalent to std::string a;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM