Search code examples
cstreamrealloc

Reading stream char by char


I'm using this function to read, char by char, a text file or a stdin input

void readLine(FILE *stream, char **string) {
    char c;
    int counter = 0;

    do {
        c = fgetc(stream);
        string[0] = (char *) realloc (string[0], (counter+1) * sizeof(char));
        string[0][counter++] = c;
    } while(c != ENTER && !feof(stream));

    string[counter-1] = '\0';
}

But when I call it, my program crashed and I really don't know why, because I don't forget the 0-terminator and I'm convinced that I stored correctly the char sequence. I've verified the string length, but it appears alright.


Solution

  • There are a few issues in this code:

    1. fgetc() returns int.
    2. Don't cast the return value of malloc() and friends, in C.
    3. Avoid using sizeof (char), it's just a very clumsy way of writing 1, so multiplication by it is very redundant.
    4. Normally, buffers are grown more than 1 char at a time, realloc() can be expensive.
    5. string[0] would be more clearly written as *string, since it's not an array but just a pointer to a pointer.
    6. Your logic around end of file means it will store the truncated version of EOF, not very nice.