1

I know from this answer that string literals are allocated statically. But is the following string concatenation also safe to use?

void someFunction(std::string& foo) {
    functionTakingCString(("start " + foo + " end").c_str());
}

Follow Up Question: As stated in the comments, this would be indeed unsafe when functionTakingCString would store that pointer. In this case, would the following be valid:

void someFunction(std::string& foo) {
    std::string bar = "start " + foo + " end";
    functionTakingCString(bar.c_str());
}
Community
  • 1
  • 1
PhilLab
  • 4,777
  • 1
  • 25
  • 77
  • 6
    As long as `functionTakingCString` doesn't store that pointer and something tries to use it beyond the lifetime of the temporary `std::string`. – LogicStuff Jan 19 '16 at 09:51
  • thanks for the comment - I added a follow up question regarding your advice – PhilLab Jan 19 '16 at 10:00
  • 1
    `bar`s lifetime would end at the `}` anyway so it's basically the same issue in your examples. – default Jan 19 '16 at 10:05

1 Answers1

3

The concatenated string is only allocated while functionTakingCString(("start " + foo + " end").c_str()); is running. Then the memory is deallocated and that pointer is no longer safe to use as you can read here. If that pointer is passed to anything that runs after functionTakingCString exits then you will have trouble.

Flash_Steel
  • 606
  • 1
  • 6
  • 16