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

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  }}
See also  How HealthStream Learning Center Supports Healthcare Education and Compliance

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist