为什么编译器在读取文本文件时会分配多余的内存?

Why does the compiler allocate excess memory when reading a text file?

我正在尝试将文本文件读入动态字符串(char * 数组)。

有人可以详细说明我的怀疑是对还是错吗?

char *FileTextRead(const char *fileName) {
    char c = 0;
    char *src = NULL;
    char *tmp = NULL;
    size_t head = 0L;
    size_t fileLength = 0L;
    FILE *textFile = fopen(fileName, "r");

    if (textFile == NULL) {
        printf("cannot open file : %s\n", fileName);
    }
    else {
        // save head position of file
        head = ftell(textFile);

        // go to end of file to get number of chars
        fseek(textFile, 0L, SEEK_END);
        fileLength = ftell(textFile);

        // rewind file to the head
        fseek(textFile, head, SEEK_SET);

        src = malloc((fileLength + 1) * sizeof(char));

        if (src == NULL) {
            printf("failed to allocate memory...\n");
        }
        else {
            tmp = src;

            while (TRUE) {
                c = getc(textFile);

                if (feof(textFile)) {
                    *tmp = '[=10=]';
                    break;
                }

                *tmp = c;
                tmp++;
            }
        }

        fclose(textFile);
    }

    return src;
}

不要忘记 fopen() 二进制模式 如果这很重要,它可以在某些平台上:

FILE *textFile = fopen(fileName, "rb");