Initializing char * with expression does not work

The following code produces incorrect output:

string my_string="My_First_Text";
char * my_pointer=(char *)(my_string+"My_Second_Text").c_str();

Why? When I initialize my_pointer, I assumed that it is not required my_pointer=new char[100]. If this assumption is false, then why?

+6
source share
5 answers

, my_string+"My_Second_Text" std::string, . , my_pointer , char, , std::string; , char std::string, . , UB.

string my_string="My_First_Text";
char * my_pointer=(char *)(my_string+"My_Second_Text").c_str();
// the temporary constructed from my_string+"My_Second_Text" has been destroyed
// my_pointer is dangled now; deference on it is UB

. .

string my_string = "My_First_Text";
my_string += "My_Second_Text";
const char * my_pointer = my_string.c_str();

BTW: std:: basic_string:: c_str const char*, - UB. char* .

, c_str(), - undefined.

+6

c_str (const char*) char*, , "my_pointer" . , ';' .
, my_pointer , .

+3

undefined. + , (my_string+"My_Second_Text").c_str(), , undefined.

c_str() const char string. string .

(my_string+"My_Second_Text") append .

std::string new_string = my_string + "My_Second_Text";
const char* char_pointer = new_string.c_str();

my_string.append("My_Second_Text");
const char* char_pointer = my_string.c_str();
+3

(my_string+"My_Second_Text").c_str() - , .

undefined, . strcpy char *.

+3

.

Bjarne ++:

void f(string& s1, string& s2, string& s3)
{
  const char∗ cs = (s1+s2).c_str();  // << Code similar to OP example
  cout << cs;
  if (strlen(cs=(s2+s3).c_str())<8 && cs[0]=='a') {
  // cs used here
  }
}

, '' !, . , , , .

s1 + s2. , C-. - - . , C-, c_str(), s1 + s2, . , cs .

cout << cs , . .

As a side note, use the appropriate C ++ listing instead of C-style casting. Read

When do you need to use static_cast, dynamic_cast, const_cast and reinterpret_cast?

+3
source

Source: https://habr.com/ru/post/1014298/


All Articles