Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 891
machine_1 Avatar asked Jul 04 '26 22:07

machine_1


2 Answers

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

like image 88
Sourav Ghosh Avatar answered Jul 06 '26 11:07

Sourav Ghosh


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.

like image 45
Danny_ds Avatar answered Jul 06 '26 11:07

Danny_ds



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!