重新分配 malloc 的字符串会导致内存泄漏吗?

Does reassigning a malloc'd string cause memory leak?

我有这个从文件中读取单词的小函数:

bool load(const char *dictionary)
{
    FILE *fp = fopen(dictionary,"r");
    //defined LENGTH = 45;
    char *word = malloc(LENGTH + 1);
   
    while(fscanf(fp,"%s[\n]",word) != EOF)
    {
        //do ... thing in here
    }

    free(word);
    return true;
}

fscanf是否会不断重新分配word导致内存泄漏?

不,这不会按照您建议的方式导致内存泄漏。 fscanf 不会重新分配 word,而是修改其 内容 。您可能希望从以下方面考虑它:fscanf 不会改变 word,但会改变 word[0]word[1]

调用 fscanf 后,word 仍将指向内存中相同的 位置 (即您从 malloc 获得的任何内容) ),但该位置的数据会有所不同。