Search code examples
cloopspointersdynamic-memory-allocationrealloc

Why realloc doesn't work in this while loop?


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);
}

Solution

  • 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 realloc function deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size. [...]

    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..