1

Okay, I'm sure there's something I'm missing here, but I have no idea what it is and I'm hoping someone could help me figure it out.

I'm reading in input from the command line and was writing a function that uses fgetc() to do so. However, a seemingly superficial change in the function causes it to behave completely differently.

This is the main() function:

while(1)
{
     char* cmd = malloc(sizeof(char) * 80);
     printf("Enter command: ");
     read_flush(cmd, 80);
     printf("%s\n", cmd);
     free(cmd);
}

And this is one of the versions of read_flush():

int read_flush(char* buffer, int count)
{
    int i, c;
    for(i = 0; i < count; i++)
    {
        c = fgetc(stdin);
        if(c == '\n' || c == EOF)
            return i;
        buffer[i] = (char)c;
    }

    return i;
}

This one works fine. You type in input and it will spit it back out. However, this next version causes main to just print "Enter command:" over and over without giving the user a chance to enter input.

int read_flush(char* buffer, int count)
{
    int i, c;
    while(i < count)    
    {
        c = fgetc(stdin);
        if(c == '\n' || c == EOF)
            return i;
        buffer[i] = (char)c;
        i++;
    }

    return i;
}

What subtlety with fgetc() am I missing here?

user1227489
  • 33
  • 1
  • 4

3 Answers3

1

Try initializing i in your second read_flush implementation.

Adam S
  • 3,065
  • 1
  • 37
  • 45
1

In the second version it looks like you are not initializing i to zero like you do in the first version. So it could be starting with a garbage value larger than count, and thus the loop never executes.

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
1

Both versions have the same error. You don't add a NUL on the end of the string. malloc does not initialize the memory that it returns.

stark
  • 12,615
  • 3
  • 33
  • 50