Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't save pointer to temporary #1368

Merged
merged 1 commit into from
Dec 21, 2020

Conversation

ellert
Copy link
Contributor

@ellert ellert commented Dec 20, 2020

The c_str() of a temporary std::string object is not valid after the
lifetime of the object expires. Consider:

$ cat temp.cpp
int main() {
  const char* c1 = std::string("ABC").c_str();
  const char* c2 = std::string("DEF").c_str();
  std::cout << c1 << std::endl;
  std::cout << c2 << std::endl;
}

$ g++ -O2 -o temp temp.cpp
$ ./temp
DEF
DEF

The memory used by the first temporary std::string is reused by the
second one, since the lifetime of the first has expired. So when the
saved c_str() of the first string is written out, it writes the second
string.

The c_str() of a temporary std::string object is not valid after the
lifetime of the object expires. Consider:

$ cat temp.cpp
int main() {
  const char* c1 = std::string("ABC").c_str();
  const char* c2 = std::string("DEF").c_str();
  std::cout << c1 << std::endl;
  std::cout << c2 << std::endl;
}

$ g++ -O2 -o temp temp.cpp
$ ./temp
DEF
DEF

The memory used by the first temporary std::string is reused by the
second one, since the lifetime of the first has expired. So when the
saved c_str() of the first string is written out, it writes the second
string.
@abh3 abh3 merged commit 24b89db into xrootd:master Dec 21, 2020
@ellert ellert deleted the no-save-pointer-to-temporary branch December 21, 2020 09:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants