0

I'm trying to implement a way to import shaders as glsl files, but it i get bash: line 1: 71365 Segmentation fault (core dumped) with the exit code 139

Here's a cut version of my code:

char* s_readShaderFile(FILE* fp){
    
    fseek(fp, 0L, SEEK_END);
    int len = ftell(fp);

    char line[256]; 
    printf("aaaaa\n");
    char* sh = alloca(len * sizeof(char));

    while(!feof(fp)){
        fgets(line, 255, fp);
        strcat(line, "\n");
        strcat(line, sh);
    }

    return sh;
}
int main (){
    FILE* f_sh_vertex = fopen("Shaders/frag.glsl", "r");
    char* sh_vertex = s_readShaderFile(f_sh_vertex);
    fclose(f_sh_vertex);

    FILE* f_sh_fragment = fopen("Shaders/frag.glsl", "r");
    char* sh_fragment = s_readShaderFile(f_sh_fragment);
    fclose(f_sh_fragment);

    return 0;
}
Lönk
  • 11
  • 2
  • https://stackoverflow.com/questions/29324796/how-to-debug-segmentation-fault – user438383 Jun 20 '21 at 09:01
  • It means there is an error in your program that is causing a crash. My best guess would be you are writing past the memory allocated for `line` by repeatedly concatenating to it. Perhaps you meant to use `sh` as the destination instead? `alloca` is also the wrong choice for an allocator since you are returning the pointer and the memory is freed when the function ends, so dangling pointer. – Retired Ninja Jun 20 '21 at 09:02
  • 1
    You should also read this: https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong – Retired Ninja Jun 20 '21 at 09:03
  • You might also consider adding some error checking to make sure the files are actually opened successfully before attempting to use or close them. Both can cause a crash or at the very least unexpected behavior. You're also not seeking back to the beginning of the file after seeking to the end to get the length. – Retired Ninja Jun 20 '21 at 09:10

0 Answers0