1

i'm trying to read vertex and fragment shader from files that look like this

#version 330 core
in vec3 ourColor;

out vec4 color;

void main()
{
    color = vec4(ourColor, 1.0f);
}

but when i'm compiling shader i get the error like 'bad syntax'. enter image description here

code that read shader code from file

const GLchar* readFromFile(const GLchar* pathToFile)
{
    std::string content;
    std::ifstream fileStream(pathToFile, std::ios::in);

    if(!fileStream.is_open()) {
        std::cerr << "Could not read file " << pathToFile << ". File does not exist." << std::endl;
        return "";
    }

    std::string line = "";
    while(!fileStream.eof()) {
        std::getline(fileStream, line);
        content.append(line + "\n");
    }

    fileStream.close();
    std::cout << "'" << content << "'" << std::endl;
    return content.c_str();
}
Oleh Kurpiak
  • 1,339
  • 14
  • 34
  • is there any trailing hidden character in your shader ? – Zermingore Sep 29 '15 at 11:25
  • @Zermingore, what do you mean? '\0'? – Oleh Kurpiak Sep 29 '15 at 11:28
  • This is basically the same problem as: http://stackoverflow.com/questions/30794981/reading-a-shader-from-a-txt-file-using-a-structure. But since the exact situation is slightly different, I'm not sure if it's close enough to be marked as duplicate. – Reto Koradi Sep 29 '15 at 12:05

1 Answers1

8

The problem here is, that the string content gets out of scope at the end of the function, which deletes the whole content. What you return is then a pointer to an already freed memory address.

const GLchar* readFromFile(const GLchar* pathToFile)
{
    std::string content; //function local variable
    ....
    return content.c_str();
} //content's memory is freed here

I see two methods here to prevent this: Either return the string itself instead of a pointer to its memory, or create a GLchar* array on the heap and copy the content there.

svarog
  • 9,477
  • 4
  • 61
  • 77
BDL
  • 21,052
  • 22
  • 49
  • 55