std::string Should Never be Initialized With a NULL Pointer

You can initialize std::string with a pointer to char. However, it does not check the pointer. When the pointer happens to be NULL the results are undefined:

 #includeusing std::string;const char * getDescription(int symbol); // returns NULL when symbol cannot not foundvoid writeToString  (string & str, int symbol){  str = getDescription(symbol);  // sloppy: initializer might be NULL; undefined behavior in this case}

To be on the safe side, you should explicitly check the pointer before you assign it:

 void writeToString ( string & str, int symbol){  const char *p = getDescription(symbol);   if (p) {     str = p; // now safe  }}
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: