[Solved] Valgrind runs infinitely with realloc but code works


It is always easier to divide program into logical bits and place them in functions.

char *addToBuff(char *buff, int ch, size_t *size)
{
    //working on local variable buff. No need for a temporary variable
    buff = realloc(buff, *size + 1);
    if(buff)
    {
        buff[*size] = ch;
        *size += 1;
    }
    return buff;
}

char *readToBuff(FILE *fi, size_t *size)
{
    char *buff = NULL;
    int ch;
    *size = 0;
    while((ch = fgetc(fi)) != EOF)
    {
        //to avoid memory leak - temporary variable needed
        char *tmp = addToBuff(buff, ch, size);
        if(!tmp) {/* handle allocation error */}
        else buff = tmp;
    }
    return buff;
}


int main(void)
{
    size_t size = 0;
    char *buff = readToBuff(stdin, &size);

    printf("read %zu chars. Buff address: '%p'\n", size, (void*)buff);
    free(buff);
}

https://godbolt.org/z/n56xsd3Pd

1

solved Valgrind runs infinitely with realloc but code works