-2

Just run this program and explain me output of last line why it prints "g" instead of "f". Here my intention is to know why it is showing previous functions return value?

#include <iostream>
#include <string>

std::string f() {
  return "f";
}

std::string g() {
  return "g";
}

int main() {
  const char * s = f().c_str();
  std::cout << "s = " << s << std::endl;
  std::cout << "g() = " << g() << std::endl;
  std::cout << "s = " << s << std::endl;
}
  • 3
    The output of c_str() is invalidated each call. You should not rely on the previous value regardless of which variable you use it for. – user2525536 Dec 04 '17 at 05:41

1 Answers1

0

That is because you are relying on a temporary value generated by "f().c_str()".The value set is not extended in the future calls to your char array i.e. s rather contains garbage since it has become dangling. Moreover it doesnt necessarily print 'g' always.

Valgrind1691
  • 182
  • 1
  • 11