[PATCH v4] libio: null terminate the buffer upon initial allocation in getdelim
Eric Blake
eblake@redhat.com
Thu Dec 4 16:55:05 GMT 2025
On Tue, Dec 02, 2025 at 08:02:58PM -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. A recent POSIX issue
> clarified that the behavior before and after that commit are allowed,
> since the contents of LINE are unspecified after -1 is returned
> [1]. However, some programs rely on the previous behavior.
>
> 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.
>
> [1] https://www.austingroupbugs.net/bug_view_page.php?bug_id=1953
>
> Suggested-by: Eric Blake <eblake@redhat.com>
> ---
> +
> + /* Test the same thing without a newline. */
> + TEST_VERIFY_EXIT (fwrite ("d", 1, 1, fp) == 1);
> + TEST_VERIFY_EXIT (fseeko (fp, -1, SEEK_CUR) == 0);
> + TEST_VERIFY (getdelim (&lineptr, &linelen, '\n', fp) == 1);
> + TEST_VERIFY (linelen > 2);
On my first read, I wondered why this wasn't 'linelen > 1'. But on
further thought, glibc guarantees that if the input size was already
large enough, we don't realloc() to something smaller. So this line
is correct for glibc behavior, even if it is stricter than what POSIX
guarantees (and after all, several aspects of this unit test are about
glibc behavior not regressing, even while providing guarantees not
mandated by POSIX).
I don't know if my review counts since I'm not a regular contributor,
but:
Reviewed-by: Eric Blake <eblake@redhat.com>
--
Eric Blake, Principal Software Engineer
Red Hat, Inc.
Virtualization: qemu.org | libguestfs.org
More information about the Libc-alpha
mailing list