[PATCH v2] libio: null terminate the buffer upon initial allocation in getdelim

Collin Funk collin.funk1@gmail.com
Sat Nov 29 01:17:42 GMT 2025


Eric Blake <eblake@redhat.com> writes:

> On Thu, Nov 27, 2025 at 01:13:43PM -0800, Collin Funk wrote:
>> Commit 33eff78c8b28adc4963987880e10d96761f2a167 caused issues in nbdkit
>> which had code similar to this to get the last line of the file:
>> 
>>     while (getline (&line, &len, fp) != -1)
>>       ;
>>     /* Process LINE.  */
>> 
>> After that commit, line[0] would be equal to '\0' instead of containing
>> the last line of the file like before that commit.
>> 
>> This patch null terminates the buffer upon getdelim/getline's initial
>> allocation. This is compatible with previous glibc versions, while also
>> protecting the caller from reading uninitialized memory if the file is
>> empty, as long as getline/getdelim does the initial allocation.
>
> Worth calling out the link to the POSIX discussion here in the commit
> message how behavior on -1 is unspecified, and therefore we are okay
> doing this?  (I see you do it in the patch proper, but that's harder
> to see when just perusing git log)

Yep, good idea.

> This tests a non-empty file that ends in \n.  Is it also worth testing
> a non-text file that ends in a partial line?  (after all, POSIX says a
> non-empty file MUST end in newline to be a text file, but that
> getline/getdelim are still well-defined on non-text files).

Sure, it is easy to add a test case for that here. Done in v3 [1].

Collin

[1] https://inbox.sourceware.org/libc-alpha/2c2c4646f2286ecdb74440192684795e8664d7a4.1764378662.git.collin.funk1@gmail.com/T/#u


More information about the Libc-alpha mailing list