0

我的代码不断从内部 c 库中抛出分段错误,我的代码如下:

        char *vertexShaderCode = (char *)calloc(1024, sizeof(char));
        FILE *shaderFile;

        shaderFile = fopen("./shaders/vertex.glsl", "r");

        if(shaderFile)
        {
            //TODO: load file
            for (char *line; !feof(shaderFile);)
            {
                fgets(line, 1024, shaderFile);
                strcat(vertexShaderCode, line);
            }

它旨在将文件中的所有数据作为 ac 字符串逐行加载。谁能帮忙?

4

1 回答 1

1

你要这个:

char *vertexShaderCode = (char *)calloc(1024, sizeof(char));
FILE *shaderFile;

shaderFile = fopen("./shaders/vertex.glsl", "r");
if (shaderFile == NULL)
{
   printf("Could not open file, bye.");
   exit(1);
}

char line[1024];
while (fgets(line, sizeof(line), shaderFile) != NULL)
{
   strcat(vertexShaderCode, line);
}

您仍然需要确保没有缓冲区溢出。realloc如果缓冲区的初始长度太小,您可能需要使用来扩展缓冲区。我把这个作为练习留给你。


你的错误代码:

    char *vertexShaderCode = (char *)calloc(1024, sizeof(char));
    FILE *shaderFile;

    shaderFile = fopen("./shaders/vertex.glsl", "r");  // no check if fopen fails

    for (char *line; !feof(shaderFile);)   // wrong usage of feof
    {                                      // line is not initialized
                                           // that's the main problem
        fgets(line, 1024, shaderFile);
        strcat(vertexShaderCode, line);    // no check if buffer overflows
    }
于 2020-05-24T16:11:15.813 回答