Lingfeng Xiong
Lingfeng Xiong

Reputation: 1171

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?

Upvotes: 1

Views: 1181

Answers (2)

Shreevardhan
Shreevardhan

Reputation: 12641

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;

Upvotes: 1

Wojtek Surowka
Wojtek Surowka

Reputation: 21003

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.

Upvotes: 7

Related Questions