Accidentally linking c_str() strings

112 views Asked by At

I'm trying to assign a string to a struct value, which works, but the value somehow links to the variable:

string tmp;
struct test_struct{
    const char *server, *user; 
};
test_struct test;

tmp = "foo";
test.server = tmp.c_str();
cout << test.server << endl;

tmp = "bar";
test.user = tmp.c_str();
cout << test.user << endl;

cout << "" << endl;

cout << test.server << endl;
cout << test.user << endl;

The output is:

foo
bar

bar
bar

Can someone please explain why this is happening?

1

There are 1 answers

1
David Schwartz On
struct test_struct{
    const char *server, *user; 
};
test_struct test;

Okay, so test.server is a pointer.

test.server = tmp.c_str(); // 1
cout << test.server << endl; // 2

tmp = "bar"; // 3
test.user = tmp.c_str();
cout << test.user << endl;

cout << "" << endl;

cout << test.server << endl; // 4

In 1, you set test.server to point to the contents of tmp. In 2, you output what test.server points to, which is fine.

In 3, you modify the contents of tmp. So now, test.server points to something that no longer exists -- the former contents of tmp.

In 4, you output what test.server points to. But that was the contents of tmp back at 1, which you destroyed in 3.

You cannot output something that you obliterated.