Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POSIX getline() - line buffer state on EOF?

Tags:

c

posix

getline

This question is in regards to the POSIX C function getline.

The documentation states that getline returns -1 on error (including EOF), but it doesn't say what becomes of lineptr or n in those situations.
I understand that some errors may be handled differently - such as a failed realloc - but what about EOF? Do lineptr and n still retain their original values? Is it implementation specific? Undefined behavior?

like image 461
Mr. Llama Avatar asked Jan 04 '23 20:01

Mr. Llama


2 Answers

If getline return an error (EOF is an error in this function). The data in the buffer should not be used.

EOF must not be returned if the function reads at least 1 byte, note that the function can return 0 in some case.

Additionally, the manual clearly say:

This buffer should be freed by the user program even if getline() failed.


In either case, on a successful call, *lineptr and *n will be updated to reflect the buffer address and allocated size respectively.

This sentence could be interpreted as the buffer is only updated on a successful call.


In my opinion, the program should log this error and continue with the data that has been already read. Note: Use feof() to know if the stream has reached the end.

like image 134
Stargateur Avatar answered Jan 14 '23 02:01

Stargateur


If you look at these POSIX docs http://pubs.opengroup.org/onlinepubs/9699919799/functions/getdelim.html you will see that the function does not return -1 if it reads the last line in the stream and the EOF occurs without a newline (i.e. the last line does not have a newline). So when you reach EOF, the contents of the buffer don't matter because getline will not have written anything into it.

like image 25
Stuart Avatar answered Jan 14 '23 00:01

Stuart