leak in GLSL shader...

Feb 20 at 12:01 PM
Edited Feb 20 at 8:35 PM
Hi!

Been getting 2 leaks because of vertexShaderSource and fragmentShaderSource but have been able to delete them using:
delete[] vertexShaderSource;
delete[] fragmentShaderSource;
Been getting HEAP CORRUPTION despite by best efforts.

Is this a VLD problem with shaders because of glDeleteShader? Please, let me know.

Thank you !
bool Shader::loadShader(std::string shaderName, ShaderType shaderType, const char* vertexShaderFile, const char* fragmentShaderFile) {

GLuint vertexShaderID, fragmentShaderID;

m_shaderType = shaderType;

m_shaderID = glCreateProgram();

seekShader(vertexShaderFile);
char* vertexShaderSource = new char[m_shaderCodeLenght + 1];
readShader(vertexShaderFile, vertexShaderSource);

seekShader(fragmentShaderFile);
char* fragmentShaderSource = new char[m_shaderCodeLenght + 1];
readShader(fragmentShaderFile, fragmentShaderSource);

compileShader(vertexShaderID, GL_VERTEX_SHADER, vertexShaderSource);
compileShader(fragmentShaderID, GL_FRAGMENT_SHADER, fragmentShaderSource);

linkShader(m_shaderID, vertexShaderID, fragmentShaderID);

glDeleteShader(vertexShaderID);
glDeleteShader(fragmentShaderID);

delete[] vertexShaderSource;    // ???
delete[] fragmentShaderSource;    // ???

glUseProgram(0);

return true;
}
Feb 20 at 2:39 PM
This is most likely not related to VLD.
My educated guess is that the code in readShader reads more byte than m_shaderCodeLenght+1.
Anyway, I would suggest to not rely on char arrays when reading files and instead read into std::string and then get the char array from std::string::c_str as suggested in http://stackoverflow.com/a/2602060/600633
Feb 20 at 7:34 PM
Thank you for your quick answer. I started with const char* because this is what compileShader() is expecting. Following your advice, I replaced it by std::string. Here below is what I am doing now, so it can help someone else. No more memory leaks, feeling great!
bool Shader::loadShader(std::string shaderName, ShaderType shaderType, std::string vertexShaderFile, std::string fragmentShaderFile) {

GLuint vertexShaderID, fragmentShaderID;

m_shaderID = glCreateProgram();

m_shaderType = shaderType;

compileShader(vertexShaderID, GL_VERTEX_SHADER, readShader(vertexShaderFile).c_str());
compileShader(fragmentShaderID, GL_FRAGMENT_SHADER, readShader(fragmentShaderFile).c_str());

linkShader(m_shaderID, vertexShaderID, fragmentShaderID);

glDeleteShader(vertexShaderID);
glDeleteShader(fragmentShaderID);

glUseProgram(0);

return true;
}


std::string Shader::readShader(std::string shaderFile) {

std::ifstream shaderStream;
std::stringstream stringStream;

shaderStream.open(shaderFile);
stringStream << shaderStream.rdbuf();//read the file
shaderStream.close();

std::string shaderSource = stringStream.str();//str holds the content of the file
logFileStderr(VERBOSE, "Code shader program \"%s\"...\n", shaderSource.c_str());

return shaderSource;
}