0
int main () {
   char dest[BIG_ENOUGH];
   memset(dest, '\0', sizeof(dest));
   strcpy(dest, func1().c_str());
   return(0);
}
std::string func1 () {
  std::string s("test");
  return s;
}

one of my workmates told me that the string on which c_str() is invoked may already be destroyed before strcpy being executed.

is this true when:

  1. compiled with msvc 2008(c++98) ,
  2. or compiled with gcc(c++11),
  3. or compiled with clang(c++11)?
BruceAuyeung
  • 155
  • 1
  • 1
  • 7
  • 1
    This is safe. Note that instead of `memset`, you could do `char dest[BIG_ENOUGH] = {0};`. Also note that zeroing destination is not required for `strcpy`. – Aykhan Hagverdili Sep 13 '20 at 12:21
  • 1
    Your workmate is incorrect. The string returned by `func1()` will exist until the end of the statement - so it (and the data pointed to by the call of `c_str()`) will be destroyed after the call `strcpy()` has completed. However, unless you have a specific requirement, `dest` should also be of type `std::string` as well. Then all `main()` needs to do is `std::string dest; dest = func1();` or (even more simply to get the same result, although the mechanics change slightly) `std::string dest = func1()`. – Peter Sep 13 '20 at 12:22
  • @Peter the above `main` is just a demo. I will do business operations on `dest` char array before `main`'s return. thanks for your reply! – BruceAuyeung Sep 13 '20 at 13:18
  • @redhatlinux10 - But that's my point. You don't need to do "business operations" using an array of `char`. You can do a lot of those operations directly on elements of the string. Worst case, create a `std::vector` from the string, and do operations on elements of the vector (or pass the address of it's first element to a function expecting a `char *`). Either approach is safer, avoids need to hard-code length, avoids needs to explicitly allocate/initialise/deallocate memory, etc. – Peter Sep 13 '20 at 13:30

1 Answers1

3

It is safe in the given example as the lifetime of the returned string ends at the end of the statement containing the function call.

In general I recommend reading https://en.cppreference.com/w/cpp/language/lifetime

afic
  • 500
  • 4
  • 13