[PATCH] libio: Fix fmemopen_write on appending condition

Rocket Ma marocketbd@gmail.com
Thu Mar 19 08:48:58 GMT 2026


* 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>
---
 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;
   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)
 	c->buffer[c->size-1] = '\0';
     }
 
-- 
2.53.0



More information about the Libc-alpha mailing list