[PATCH v4] libio: Fix fmemopen_write on appending mode (BZ 34006)

Rocket Ma marocketbd@gmail.com
Wed May 13 16:12:42 GMT 2026


* libio/fmemopen.c: Reference pos the variable instead of c->pos.
On the edge case, one byte should be written at the end of buffer,
instead of returning error.

Signed-off-by: Rocket Ma <marocketbd@gmail.com>
---
Fixed title and DCO.

Actually I think it makes no sense not to deal with the case I mentioned
in bug report[1]. I still insist on that the current code is not correct.
Printed buf should all be buf[0..9]=abc..XXXXX if the stream is opened
for writing.

[1]: https://sourceware.org/bugzilla/show_bug.cgi?id=34006#c1
---
 libio/Makefile       |  1 +
 libio/bug-fmemopen.c | 37 +++++++++++++++++++++++++++++++++++++
 libio/fmemopen.c     |  2 +-
 3 files changed, 39 insertions(+), 1 deletion(-)
 create mode 100644 libio/bug-fmemopen.c

diff --git a/libio/Makefile b/libio/Makefile
index 684697fb9e..a8011a7f0d 100644
--- a/libio/Makefile
+++ b/libio/Makefile
@@ -70,6 +70,7 @@ routines_no_fortify += \
   # routines_no_fortify
 
 tests = \
+  bug-fmemopen \
   bug-fopena+ \
   bug-fseek \
   bug-ftell \
diff --git a/libio/bug-fmemopen.c b/libio/bug-fmemopen.c
new file mode 100644
index 0000000000..923649e887
--- /dev/null
+++ b/libio/bug-fmemopen.c
@@ -0,0 +1,37 @@
+/* Regression test for fmemopen bug BZ 34006.
+   Copyright The GNU Toolchain Authors.
+   This file is part of the GNU C Library.
+
+   The GNU C Library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 2.1 of the License, or (at your option) any later version.
+
+   The GNU C Library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with the GNU C Library; if not, see
+   <https://www.gnu.org/licenses/>.  */
+
+#include <support/xstdio.h>
+#include <support/check.h>
+#include <stdio.h>
+
+static int
+do_test (void)
+{
+  char buf[5] = "1";
+  FILE *fp = xfmemopen (buf, 4, "a+");
+  setbuf (fp, NULL);
+  TEST_VERIFY (fseek (fp, 3, SEEK_SET) == 0);
+  TEST_VERIFY (fwrite ("XXXX", 1, 4, fp) > 0);
+  TEST_COMPARE_STRING (buf, "1XXX");
+  fclose (fp);
+
+  return 0;
+}
+
+#include <support/test-driver.c>
diff --git a/libio/fmemopen.c b/libio/fmemopen.c
index f2ae1338d3..cdc3a3476e 100644
--- a/libio/fmemopen.c
+++ b/libio/fmemopen.c
@@ -71,7 +71,7 @@ fmemopen_write (void *cookie, const char *b, size_t s)
 
   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;
-- 
2.54.0


More information about the Libc-alpha mailing list