Dragomir
Dragomir

Reputation: 43

Following code for loading shaders in openGL gives a heap corruption error

I am writing a function to parse shader code to c++ strings which openGL compiles.

ShaderSource LoadShaders(const string &filepath)
{
    std::ifstream file(filepath);

    enum class MODES
    {
        NONE = -1, VS = 0, FS = 1
    };



    string line;
    std::stringstream ss[2];
    MODES mode = MODES::NONE;

    while (getline(file, line))
    {
        if (line.find("#shader") != string::npos)
        {
            if (line.find("vertex") != string::npos)
                mode = MODES::VS;

            else if (line.find("fragment") != string::npos)
                mode = MODES::FS;
        }
        else
        {
            ss[(int)mode] << line << "\n";
        }
    }
    file.close();
    return { CompileShader(GL_VERTEX_SHADER, ss[0].str().c_str()), 
             CompileShader(GL_FRAGMENT_SHADER, ss[1].str().c_str()) };
}

I get heap corruption error after block #231 randomly on lines std::ifstream file(filepath); to while loop.

Upvotes: 1

Views: 161

Answers (1)

datenwolf
datenwolf

Reputation: 162164

You never check, that in

        ss[(int)mode] << line << "\n";

mode is a actually a valid value. You default initialize it to NONE which is -1. So if the first line of your shader file does not match the requirements to set a proper mode, you're going to end up writing out-of-bounds.

Upvotes: 2

Related Questions