Search code examples
cstdio

Null-termination guarantees by fgets if NULL is returned


While reading the C99 draft ISO/IEC 9899:TC2 WG14/N1124, I stumbled upon some statements that worries me:

Is the string/buffer given to fgets also guaranteed to be null terminated if fgets returns NULL?

§7.19.7.2 states in the description

A null character is written immediately after the last character read into the array.

But under return:

If a read error occurs during the operation, the array contents are indeterminate and a null pointer is returned.

So the last statement implies in my interpretation that this guarantee is not given in any NULL-returning case. I'm already about to correct http://en.cppreference.com, since they are using errno, which fgets isn't obliged to set. But I'm not sure if I maybe misinterpret this.


Solution

  • You interpret the standard correctly. In case there are errors, the function will return NULL and the contents of the buffer are not to be trusted.

    This allows fgets to read straight into the target buffer without any double buffer in between. So upon error half-ways through the expected data, it may simply stop and return NULL.

    Also note this special case (7.21.7.2):

    If end-of-file is encountered and no characters have been read into the array, the contents of the array remain unchanged and a null pointer is returned.