[PATCH] Discard any push-back from a memory stream before finishing it (bug 34020)

DJ Delorie dj@redhat.com
Mon Mar 30 19:07:52 GMT 2026


Andreas Schwab <schwab@suse.de> writes:
> This makes sure that the write base is pointing to the main area, not the
> backup area.

So I just realized, after working in this code for years, that "backup"
here doesn't mean "in case we run out" it means "going backwards" :-P No
wonder it seemed weird to me.

One question below about fseek, but otherwise OK.

> diff --git a/libio/memstream.c b/libio/memstream.c
> index 0456adb92f..fcc925df87 100644
> --- a/libio/memstream.c
> +++ b/libio/memstream.c
> @@ -100,6 +100,9 @@ _IO_mem_finish (FILE *fp, int dummy)
>  {
>    struct _IO_FILE_memstream *mp = (struct _IO_FILE_memstream *) fp;
>  
> +  if (_IO_in_backup (fp))
> +    _IO_switch_to_main_get_area (fp);
> +
>    *mp->bufloc = (char *) realloc (fp->_IO_write_base,
>  				  fp->_IO_write_ptr - fp->_IO_write_base + 1);
>    if (*mp->bufloc != NULL)

Ok.

> diff --git a/libio/tst-memstream6.c b/libio/tst-memstream6.c
> +static void
> +mcheck_abort (enum mcheck_status ev)
> +{
> +  printf ("mecheck failed with status %d\n", (int) ev);
> +  exit (1);
> +}

Ok.

> +void
> +do_test_ungetc_1 (void)
> +{
> +  CHAR_T *buf;
> +  size_t size;
> +
> +  FILE *fp = OPEN_MEMSTREAM (&buf, &size);
> +  TEST_VERIFY_EXIT (fp != NULL);
> +
> +  FPUTC (W('A'), fp);
> +  fflush (fp);
> +
> +  TEST_COMPARE (FGETC (fp), W('A'));

I would have expected you to need an fseek here.  fflush() on a
memstream synchronizes the buffer and size pointers but says nothing
about moving the file pointer.

> +  TEST_COMPARE (UNGETC (W('B'), fp), W('B'));
> +
> +  TEST_COMPARE (fclose (fp), 0);
> +
> +  TEST_COMPARE (buf[0], W('A'));
> +
> +  free (buf);
> +}

Ok.

> +void
> +do_test_ungetc_2 (void)
> +{
> +  CHAR_T *buf;
> +  size_t size;
> +
> +  FILE *fp = OPEN_MEMSTREAM (&buf, &size);
> +  TEST_VERIFY_EXIT (fp != NULL);
> +
> +  TEST_COMPARE (UNGETC (W('A'), fp), W('A'));
> +
> +  TEST_COMPARE (fclose (fp), 0);
> +
> +  TEST_COMPARE (buf[0], 0);
> +
> +  free (buf);
> +}

Ok.

> +static int
> +do_test (void)
> +{
> +  mcheck_pedantic (mcheck_abort);
> +
> +  do_test_ungetc_1 ();
> +  do_test_ungetc_2 ();
> +
> +  return 0;
> +}

Ok.

> diff --git a/libio/tst-wmemstream6.c b/libio/tst-wmemstream6.c
> +#define TEST_WCHAR
> +#include <libio/tst-memstream6.c>

Ok.

> diff --git a/libio/wmemstream.c b/libio/wmemstream.c
> index d0c639be70..a0c61a627f 100644
> --- a/libio/wmemstream.c
> +++ b/libio/wmemstream.c
> @@ -101,6 +101,9 @@ _IO_wmem_finish (FILE *fp, int dummy)
>  {
>    struct _IO_FILE_wmemstream *mp = (struct _IO_FILE_wmemstream *) fp;
>  
> +  if (_IO_in_backup (fp))
> +    _IO_switch_to_main_wget_area (fp);
> +
>    *mp->bufloc = (wchar_t *) realloc (fp->_wide_data->_IO_write_base,
>  				     (fp->_wide_data->_IO_write_ptr
>  				      - fp->_wide_data->_IO_write_base + 1)

Ok.



More information about the Libc-alpha mailing list