简体   繁体   中英

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.

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?

The std::string - as opposite to inherited from C char* strings - always holds a valid string. It may be empty, but it cannot be 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.

Just use

std::string a;

and then a will be initialised empty string.

NULL is assigned only to pointer types and that too in C. The C++ way is std::nullptr_t or nullptr . 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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