Why does c_str () return the same value for two different lines?

Given the simple file upload function,

std::string load_file(const std::string &filename) {
    std::ifstream     file(filename);
    std::string       line;
    std::stringstream stream;
    while (std::getline(file, line)) {
        stream << line << "\n";
    }
    return stream.str();
}

Why another_filedoes the following print content twice?

const char *some_file = load_file("some_file").c_str();
const char *another_file = load_file("another_file").c_str();
printf("%s", some_file);
printf("%s", another_file);
+4
source share
2 answers

The code is broken. You call c_str()on a temporary object that is immediately destroyed. This means that the values ​​returned c_str()are not valid.

You need to make sure that the returned objects are std::stringpreserved, at least as long as you hold the pointer returned by the call c_str(). For instance:

std::string some_file = load_file("some_file");
std::string another_file = load_file("another_file");
printf("%s", some_file.c_str());
printf("%s", another_file.c_str());
+14
source

In a line like this:

const char *some_file = load_file("some_file").c_str();

load_file() std::string, .c_str() .

, , .c_str(), - . "" ( ), .

"" , load_file(), , . . .

String , std::string, ++ C. std::string, ++.

.c_str() C ( printf()).

, :

// load_file() returns a std::string, so just keep using std::string.
// Note that returning std::string is efficient thanks to RVO/NRVO 
// and C++11 move semantics. 
std::string some_file = load_file("some_file");

// Idem for this:
std::string another_file = load_file("another_file");

// Convert from std::string to raw C string pointers at the C boundary
printf("%s\n", some_file.c_str());
printf("%s\n", another_file.c_str());

:

printf("%s\n", load_file("some_file").c_str());
printf("%s\n", load_file("another_file").c_str());

, , , (.. , load_file(), std::string), printf() , .c_str(), , printf() .

+3

Source: https://habr.com/ru/post/1536139/


All Articles