Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Does This Function Segfault? [closed]

This has been troubling me for some time; this function doesn't even return, it just segfaults. I specify a correct file location, I check for errors at every possible point in the function, I don't understand?

GLchar* getShaderString(const GLchar* file_path){
    FILE* srcfile = NULL;
    if(!(srcfile = fopen(file_path, "r")))
        return(NULL);
    fseek(srcfile, 0l, SEEK_END);
    long len;
    if((len = ftell(srcfile)) == -1)
        return (NULL);
    fseek(srcfile, 0l, SEEK_SET);
    GLchar* buff;
    if(!(buff = malloc(len + 1)))
        return (NULL);
    fread((GLvoid*)buff, len, 1, srcfile);
    fclose(srcfile);
    buff[len + 1] = '\0';
    return (buff);
}
like image 835
Shokwav Avatar asked Dec 07 '25 04:12

Shokwav


2 Answers

buff[len + 1] = '\0';

should be:

buff[len] = '\0';

You have len + 1 elements in your array, your last element is at index len.

like image 181
ouah Avatar answered Dec 08 '25 17:12

ouah


fopen works on const char* not const GLchar*.

Also, buff[len+1] = '\0'; should be buff[len] = '\0';.

like image 24
CrazyCasta Avatar answered Dec 08 '25 18:12

CrazyCasta