Follow @Openwall on Twitter for new release announcements and other news
[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-ID: <20190222050442.GG19969@voyager>
Date: Fri, 22 Feb 2019 06:04:42 +0100
From: Markus Wichmann <nullplan@....net>
To: musl@...ts.openwall.com
Subject: Re: fgets() doesn't call fsync() before getting input

On Thu, Feb 21, 2019 at 03:16:23PM -0500, James Larrowe wrote:
> Sorry, this was a typo. I meant fflush(). However, it's still not called.
> It's fixed in my program now, however I'm not sure what to do in this case.
> Do I just call ffush() on stdin, stdout, and stderr or do I send a patch to
> fgets()?
> 

You call fflush(stdout). stderr is already unbuffered, so flushing it
only makes sense if you used setvbuf() on it beforehand. Why would you,
though? Being unbuffered is sort of the defining feature of stderr.

Also fflush(stdin) is undefined behavior. fflush() is only defined for
output streams. Since you are asking beginner's questions, you are
likely to come accross the following idiom in C tutorials:

    cnt = scanf("Some format", some variables);
    fflush(stdin);

Or maybe the other way round. The reason for this is that scanf()
terminates at the newline character at the end of the line you inserted,
but doesn't consume it. So the next scanf() will read it as the first
thing. The format will likely not allow for whitespace at the start of
input, and so the scanf() will fail.

The solution is to either allow for the newline by starting the scanf
format with a space, or to use:

    char buf[some appropriate line length];
    if (fgets(buf, sizeof buf, stdin))
        cnt = sscanf(buf, "Some format", some variables);

Ciao,
Markus

Powered by blists - more mailing lists

Confused about mailing lists and their use? Read about mailing lists on Wikipedia and check out these guidelines on proper formatting of your messages.