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.
There are a few issues in this code:
fgetc()
returns int
.malloc()
and friends, in C.sizeof (char)
, it's just a very clumsy way of writing 1
, so multiplication by it is very redundant.realloc()
can be expensive.string[0]
would be more clearly written as *string
, since it's not an array but just a pointer to a pointer.EOF
, not very nice.