为什么realloc在这个while循环中不起作用?

mac*_*e_1 2 c pointers loops realloc dynamic-memory-allocation

我很想知道为什么realloc()在我的循环中不起作用.我做了一个grep函数,我在一个大文本文件上测试,突然程序崩溃告诉我"堆的腐败"所以我决定分解它并尝试它规模较小,但问题仍然存在.可以解释一下有什么问题吗?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void grep(const char *Pattern,FILE *file);

int main(void)
{
    FILE *file;
    if(fopen_s(&file,"file.txt","r"))
        return 1;
    grep("word",file);
    fclose(file);
    return 0;
}

void grep(const char *Pattern,FILE *file)
{
    size_t size = 5*sizeof(char);
    char *_Buf = (char*)malloc(size);
    int n = 0, c;
    while(c=getc(file))
    {
        _Buf[n++] = c;
        if(c == '\n' || c == EOF)
        {
            _Buf[n] = '\0';
            if(strstr(_Buf,Pattern))
                printf("%s",_Buf);
            if(c == EOF)
                break;
            n = 0;
        }
        if(n == size)
        {
            size += 5;
            realloc(_Buf,size);
        }
    }
    free(_Buf);
}
Run Code Online (Sandbox Code Playgroud)

Sou*_*osh 5

调用realloc()指针不会调整旧指针.它解除分配旧指针并返回包含新分配的新指针.之后你需要使用返回的指针.

C11标准,章节§7.22.3.5,realloc功能

void *realloc(void *ptr, size_t size);

realloc函数释放指向的旧对象,ptr并返回指向具有指定大小的新对象的指针size.[...]

因此,您需要收集返回的指针,检查NULL并将其分配回前一个指针,就像您可能一样.

也就是说,请参阅此讨论,了解为什么不投出malloc()和家人的回报价值C..