[PATCH] libio: Fix fmemopen_write on appending condition

Adhemerval Zanella Netto adhemerval.zanella@linaro.org
Thu Mar 19 16:28:13 GMT 2026



On 19/03/26 05:48, Rocket Ma wrote:
> * libio/fmemopen.c: reference pos the variable instead of c->pos
> 
> To reproduce, write a C unit with the following code and then compile it
> and run it, should expect an output with "1 No space left on device".
> Apparently, for appending mode, there is enough room to write some
> bytes, but it didn't. `c->pos` should be corrected to `pos`.
> 
>     char buf[5] = "1";
>     FILE *fp = fmemopen(buf, 4, "a+");
>     fseek(fp, 3, SEEK_SET);
>     fwrite("XXXX", 1, 4, fp);
>     int rc = fflush(fp);
>     printf("%s %m\n", buf);
> 
> I could send another patch once Bug 34006 is resolved.
> 
> Signed-off-by: Rocket Ma <marocketbd@gmail.com>

Could you add a new regression for this issue (similar to ./stdio-common/tst-fmemopen*.c)?


> ---
>  libio/fmemopen.c | 6 +++---
>  1 file changed, 3 insertions(+), 3 deletions(-)
> 
> diff --git a/libio/fmemopen.c b/libio/fmemopen.c
> index f2ae1338d3..6232d273b5 100644
> --- a/libio/fmemopen.c
> +++ b/libio/fmemopen.c
> @@ -65,13 +65,13 @@ fmemopen_read (void *cookie, char *b, size_t s)
>  static ssize_t
>  fmemopen_write (void *cookie, const char *b, size_t s)
>  {
> -  fmemopen_cookie_t *c = (fmemopen_cookie_t *) cookie;;
> +  fmemopen_cookie_t *c = (fmemopen_cookie_t *) cookie;

Although this is not incorrect, I think for the bugfix it would be good to
avoid style changes.

>    off64_t pos = c->append ? c->maxpos : c->pos;
>    int addnullc = (s == 0 || b[s - 1] != '\0');
>  
>    if (pos + s > c->size)
>      {
> -      if ((size_t) (c->pos + addnullc) >= c->size)
> +      if ((size_t) (pos + addnullc) >= c->size)
>  	{
>  	  __set_errno (ENOSPC);
>  	  return 0;
> @@ -88,7 +88,7 @@ fmemopen_write (void *cookie, const char *b, size_t s)
>        if (c->maxpos < c->size && addnullc)
>  	c->buffer[c->maxpos] = '\0';
>        /* A null byte is written in a stream open for update iff it fits.  */
> -      else if (c->append == 0 && addnullc != 0)
> +      else if (c->append == 0 && addnullc)

Same and glibc style prefer no implicit checks.

>  	c->buffer[c->size-1] = '\0';
>      }
>  

The fix looks good, thanks for working on this.


More information about the Libc-alpha mailing list