Reputation: 1171
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
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
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