I want to get a log message from a C library. The library provides two functions :
int get_log_length(); // Returns the length of the string, including the terminating null character
void get_log(char *buffer); // Writes the log into buffer
I want to write that log into a std::string and return it. The normal way (I think) would be :
std::string get_log() {
int length = get_log_length();
char *buffer = new char[length];
get_log(buffer);
std::string str(buffer, length - 1);
delete[] buffer;
return str;
}
But I would like to skip using a buffer, so I thought of doing this :
std::string get_log() {
std::string str;
str.reserve(get_log_length());
get_log(str.data()); // Bad: undefined behaviour
return str;
}
But the size() of the std::string would remain unchanged, and would result in undefined behaviour (cf. cppreference).
Is there a way to only write the log once ?