1

This is the entire program:

#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;

const char* str_c = "\0";

const char* function() {
    string str_cpp = "John Doe";
    str_c = str_cpp.c_str();
    cout << str_cpp.c_str() << "\n";
    cout << str_c << "\n";
    return str_c;
}

int main() {
    cout << function() << "\n\n";
    system("PAUSE");
    return 0;
}

And this is what it returns:

  • John Doe
  • John Doe
  • ╠╠╠╠╠╠╠╠

I have no clue why the string to which str_c points suddenly went missing. Is it because its contents were created within function() and therefore had a shorter lifespan?

Zero
  • 11,593
  • 9
  • 52
  • 70
Johnny
  • 1
  • 2
  • This doesn't address the question, but `"\0"` should just be `""`. The compiler will put the nul terminator in; you don't need to code it explicitly. – Pete Becker Nov 27 '18 at 23:30
  • What compiler are you using? I'm on mac, I compiled with g++ and clang++ and it worked. I had to remove the system call (mac doesn't have pause command). – Dan Nov 28 '18 at 00:33
  • 1
    @Dan Why is `std::endl` instead of `\n` a better practice? `std:endl` flushes the output stream which is costly (and rarely needed). [Use of std::endl in place of '\n', encouraged by some sources, may significantly degrade output performance.](https://en.cppreference.com/w/cpp/io/manip/endl) – Ted Lyngmo Nov 28 '18 at 00:49

0 Answers0