Search code examples
copenglglslshader

GLSL Shader Compilation Fails (But Only Sometimes)


I am learning OpenGL and right now I am stuck on loading shaders. 90% of the time, this code works. The other 10% of the time, I get the following error for the vertex shader's compilation (I removed the error logging from the code below for easier readability.):

Vertex shader failed to compile with the following errors:
ERROR: 0:16: error(#132) Syntax error: "<" parse error
ERROR: error(#273) 1 compilation errors.  No code generated

Shader loading code:

unsigned int LoadShader(const char *path_vert, const char *path_frag) { // Returns shader program ID.
    unsigned int shader_program;
    FILE *file;
    char *source_vert, *source_frag;
    unsigned int file_size;
    
     // Read vertex shader.
    file = fopen(path_vert, "rb");
    
    fseek(file, 0, SEEK_END);
    file_size = ftell(file);
    fseek(file, 0, SEEK_SET);
    
    source_vert = (char*)malloc(file_size + 1);
    fread(source_vert, 1, file_size, file);
    
     // Read fragment shader.
    file = fopen(path_frag, "rb");
    
    fseek(file, 0, SEEK_END);
    file_size = ftell(file);
    fseek(file, 0, SEEK_SET);
    
    source_frag = (char*)malloc(file_size + 1);
    fread(source_frag, 1, file_size, file);
    
    fclose(file);

     // Make sure the shader sources aren't garbage.
    printf("%s\n\n %s\n", source_vert, source_frag);
    
    // Create vertex shader.
    unsigned int vert_shader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vert_shader, 1, &source_vert, NULL);
    glCompileShader(vert_shader);
    
    // Create fragment shader.
    unsigned int frag_shader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(frag_shader, 1, &source_frag, NULL);
    glCompileShader(frag_shader);
    
    // Create shader program.
    shader_program = glCreateProgram();
    glAttachShader(shader_program, vert_shader);
    glAttachShader(shader_program, frag_shader);
    glLinkProgram(shader_program);

     // Clean up the extra bits.
    glDeleteShader(vert_shader);
    glDeleteShader(frag_shader);
    free(source_vert);
    free(source_frag);
    
    return shader_program;
}

Vertex shader:

#version 460 core

layout (location = 0) in vec3 a_pos
layout (location = 1) in vec2 a_tex_coord

out vec2 tex_coord;

void main() {
    gl_Position = vec4(a_pos, 1.0f);
    tex_coord = a_tex_coord;
}

Fragment shader:

#version 460 core

uniform sampler2D tex0;

in vec2 tex_coord;

out vec4 frag_color;

void main() {
    frag_color = texture(tex0, tex_coord);
}

I am compiling for C99 with GCC using VS Code. Thanks for reading!


Solution

  • I suspect that the problem is that source_vert and source_frag buffers are not null-terminated. You allocate file_size + 1 bytes for each but then only fill file_size bytes by reading from file leaving last byte filled with garbage.