Reputation: 155
I'm using a stringstream to get the content of a textfile (actually, it's a shader code source), in order to pass it to a function that take a const char* const* (glShaderSource). At first, I did that
std::stringstream buffer;
buffer << input.rdbuf();
char const *code = buffer.str().c_str();
glShaderSource(id, 1, &code, 0);
It didn't work, for the reason that the content of code was not what was expected. Actually, if I'm doing this :
std::stringstream buffer;
buffer << input.rdbuf();
char const *code = buffer.str().c_str();
printf("Code*: %p\n", code);
printf("Buff*: %p\n", buffer.str().c_str());
printf("Code0: %c\n", code[0]); // ERROR: prints garbage.
printf("Buff0: %c\n", buffer.str().c_str()[0]);
printf("Code1*: %p\n", &code[1]); // ERROR: prints garbage.
printf("Buff1*: %p\n", &buffer.str().c_str()[1]);
printf("Code1: %c\n", code[1]);
printf("Buff1: %c\n", buffer.str().c_str()[1]);
I get the same outputs for the pointer values, the correct outputs for the characters in the buffer, but random ones for the content of code.
Now, if I use a function like this :
void workaround(char const *code) {
printf("Code*: %p\n", code);
printf("Code: %s\n", code);
}
-------------------------------------
std::stringstream buffer;
buffer << input.rdbuf();
workaround(buffer.str().c_str());
printf("Buff*: %p\n", buffer.str().c_str());
printf("Buff: %s\n", buffer.str().c_str());
I get the correct values for the pointers and the string contents.
Why does this code work and not the first one ?
Upvotes: 0
Views: 101
Reputation: 155
I've found the problem: the string returned by std::stringstream is temporary and is valid only until the end of the expression.
To expand the duration of validity of buffer.str(), it is possible to create a reference over the object. The life expectancy of the value will be extended to the one of the reference.
The following code works :
std::string const &string = buffer.str();
char const *code = string.c_str();
glShaderSource(id, 1, &code, 0);
Upvotes: 2