为什么在我的字符串中随机替换单个字符?

时间:2016-10-16 18:10:44

标签: string opengl stdio

我正在使用MinGW32版本4.9.3在OpenGL4中编写游戏。它包含这个功能:

void loadShaderFile(GLuint* shader, const char* filename, GLenum type){
    const char* path = "./res/shaders/"; // TODO: Proper path.
    char* fullPath;
    char* sourceCode;
    long fileLength;
    FILE* f;

    fullPath = malloc(strlen(filename) * sizeof(char) + sizeof(path) + 1);
    if(!fullPath){
        // TODO: Proper error handling.
        fprintf(stderr, "Error: Could not allocate char* fullPath in void loadShaderFile()!");
        exit(EXIT_FAILURE);
    }
    strcpy(fullPath, path);
    strcat(fullPath, filename);

    printf("%s\n", fullPath); // Prints correct path.
    printf("%s\n", fullPath);

    f = fopen(fullPath, "rb"); // Does not open.
    if(!f){
        // TODO: Proper error handling.
        fprintf(stderr, "Error: Could not open %s in void loadShaderFile()!", fullPath); // Prints different string.
        free(fullPath);
        exit(EXIT_FAILURE);
    }
    fseek(f, 0, SEEK_END);
    fileLength = ftell(f);
    fseek(f, 0, SEEK_SET);

    sourceCode = malloc(fileLength * sizeof(char) + 1);
    if(!sourceCode){
        // TODO: Proper error handling.
        fprintf(stderr, "Error: Could not allocate char* sourceCode in void loadShaderFile()!");
        fclose(f);
        free(fullPath);
        exit(EXIT_FAILURE);
    }
    fread(sourceCode, 1, fileLength, f);
    *(sourceCode + fileLength) = '\0';

    *(shader) = glCreateShader(type);
    glShaderSource(*(shader), 1, (char const * const *)&sourceCode, NULL); // Fucking pointers.
    glCompileShader(*(shader));

    fclose(f);
    free(sourceCode);
    free(fullPath);
}

以下是loadShaderFile(&vs, "defaultVertexShader.glsl", GL_VERTEX_SHADER)

时的输出
./res/shaders/defaultVertexShader.glsl
./res/shaders/defaultVertexShader.glsl
Error: Could not open ./res/shaders/defaultVertexShader.g$sl in void loadShaderFile()!

正如您所看到的,fullPath包含了defaultVertexShader.glsl的正确路径,但是一旦调用fopen,它就会将文件扩展名中的第一个l替换为随机ASCII字符,每次它都是一个不同的字符。跑了。我认为它可能是stdio中的一个错误。

1 个答案:

答案 0 :(得分:1)

你有

const char* path = ...
fullPath = malloc(strlen(filename) * sizeof(char) + sizeof(path) + 1);

path不是数组,而是指针,因此sizeof(path)将产生sizeof(const char *)