string append string_view unexpected result

123 Views Asked by At
#include <iostream>
std::string_view return_string_view();
using namespace std;
int main()
{
  string got;
  auto peeked = return_string_view();
  got += peeked;
  cout << got << endl;
  return 0;
}
string_view return_string_view()
{
  string const s = string().assign( 2, 'x' );
  auto sv = string_view( s.c_str() );
  return sv;
}

os version

Linux vm 5.19.0-45-generic #46-Ubuntu SMP PREEMPT_DYNAMIC Wed Jun 7 09:08:58 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux

gcc version

Linux vm 5.19.0-45-generic #46-Ubuntu SMP PREEMPT_DYNAMIC Wed Jun 7 09:08:58 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux

debug info final result

expected return "xx",but why return weird string?

2

There are 2 best solutions below

2
Ted Lyngmo On BEST ANSWER

s is destroyed at the end of the scope (when return_string_view returns) so the std::string_view returned by return_string_view is a view over a std::string that has stopped existing.

Keep in mind that a string_view doesn't own the memory it's a view over. It is typically implemented as a pointer and a length, but the actual data is owned by s.

Reading from the memory pointed out by the string_view makes the program have undefined behavior. The program could crash, or worse.

0
Lars Nielsen On

when the return_string_view function returns the string dies and the pointer from s.c_str() doesn't point to what you expect anymore.

As @heap-underrun points out, it is noted on cppreference, it is your job to ensure that the pointed to array is still alive. Which it is not.