I am testing opengl things in c++, the thing is that I create a class File
with static functions to use them in different parts of the code.
/* utils.hpp */
class File {
public:
static std::string Read(std::string path);
};
/* utils.cpp */
std::string File::Read (std::string path) {
std::string content = "";
std::ifstream file (path, std::ios::binary);
if (file) {
/* move the pointer to the end and resize the content string */
file.seekg(0, std::ios::end);
content.resize(file.tellg());
/* move the pointer to the beginning and read the content */
file.seekg(0, std::ios::beg);
file.read(&content[0], content.size());
}
/* Close the handle file and return the content */
file.close();
return content;
}
My problem is that when I try to read the files where I store the shader code, I have to call File::Read()
2 times, the first for the vertex and the second for the fragment shader, and I store the values in different variables, but the 2 variables end with the value That is, the last value returned by the function.
/* Get the source code of the fragment and vertex shaders */
// testFile1.txt = "test 1"
// testFile2.txt = "test 2"
const char* vertexSource = File::Read("textFile1.txt").c_str(); // vertexSource = "test 2"
const char* fragmentSource = File::Read("textFile2.txt").c_str(); // fragmentSource = "test 2"
std::cout << vertexSource << std::endl;
std::cout << fragmentSource << std::endl;
program output:
~$ mingw32-make -s
~$ ./bin/build/main.exe
test 2
test 2
~$
Does anyone know what could be going on. Thank you very much
You have come across what is known as " undefined behavior " (IC). When the compiler encounters a CI it can make bizarre decisions 1 like making your code not work, work strangely (as you are), or some people believe it can summon daemons into your nostrils .
Undefined behavior? Where!?
The CI in your code is specifically here:
Undefined behavior? Why!?
What you are passing exactly to give rise to the CI is the following:
Read
.}
).return
.return
leaves the scope of the function, the destructor of the local variable is called .std::string
using the local variable as the copy source. Undefined behavior , we are copying data that has been deleted.What do I do to fix it?
There are two undefined behaviors to dodge, it can be done in various ways:
string::c_str()
on a temporary : Extend the life of the temporary or create a copy, but you shouldn't read the internal memory of a temporary object: This fixes CI7, but thevertexSource
and pointersfragmentSource
will be valid only as long as thev
and objectsf
are alive.destination
to an external scope, you avoid IC5 and IC7.1 Bizarro, ra : From it. bizarre 'angry' adj. brave (‖ risky).