I am anxious to know why realloc()
doesn't work in my loop.I made a grep
function which i tested on a large text file and suddenly the program crashed telling me "corruption of the heap" so I decided to break it up and try it on a smaller scale,but the problem persist.Can someone explain what is wrong?
#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);
}