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);
}
Calling realloc() on a pointer does not adjust the old pointer. It deallocates the old pointer and returns a new pointer containing the new allocation. You need to make use of the returned pointer afterwards.
From the C11 standard, chapter §7.22.3.5, The realloc function
void *realloc(void *ptr, size_t size);The
reallocfunction deallocates the old object pointed to byptrand returns a pointer to a new object that has the size specified bysize. [...]
So, you need to collect the returned pointer, check against NULL and assign it back to the previous pointer, as you may.
That said, please see this discussion on why not to cast the return value of malloc() and family in C..
You are not assinging the returned pointer of realloc() to a variable/pointer:
realloc(_Buf,size);
Use:
char * _New_Buf = realloc(_Buf,size);
if(_New_Buf != NULL)
_Buf = _NewBuf;
else
; // add some error handling here
Otherwise, free() will also be free-ing the wrong memory pointed to by a possible invalid _Buf.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With