Search code examples
ccomparisonsize-t

size_t comparison to 0 does not work, comparison to -1 does


I'm trying to write extremely simple code to read input from stdin, one line at a time.

The code

size_t size = 0;
size_t length = 1;
char* text = NULL;

while (length > 0) {
    length = getline(&text, &size, stdin);
}

Does not terminate on EOF, when length = -1, while

while (length != -1) {
    length = getline(&text, &size, stdin);
}

does.

How is this at all possible? Thanks.


Solution

  • The problem is here:

    size_t length = 1;
    

    The return of getline() is ssize_t, not size_t

    ssize_t is used for functions that can return a negative error indications (eg -1 per definition of getline()) or a positive byte value. size_t should be used only for functions that are limited to returning positive byte values.

    Use ssize_t length = 1; as a replacement declaration.

    Aside - In your example you use EOF in helping to describe your unexpectedly missing error condition. As @Jonathan Leffler noted in comments, it is noteworthy that because this is tagged C (and not C++), and because getline() is not part of the standard C libraries, it must be either a GNU extension or a POSIX implementation. Both explicitly define the return error condition as being represented by -1 not EOF.

    • GNU - "If an error occurs or end of file is reached without any bytes read, getline returns -1."
    • POSIX - "...Both functions return -1 on failure to read a line..." (the other being getdelim().)

    The importance of this fun fact is minimized as there are no systems for which EOF is defined as anything other than -1. :)