* src/csplit.c (load_buffer): Continue reading while we haven't read a
newline and we have buffer space available.
* tests/csplit/csplit.sh: Add a test case.
* NEWS: Mention the bug fix.

Discovered by Anthropic's OSS Scanner, as bug ANT-2026-KDIGA4TE.
---
 NEWS                   |  5 +++++
 src/csplit.c           | 14 +++++++++++++-
 tests/csplit/csplit.sh | 17 +++++++++++++++++
 3 files changed, 35 insertions(+), 1 deletion(-)

diff --git a/NEWS b/NEWS
index 8b1513fe4..93af8a0ae 100644
--- a/NEWS
+++ b/NEWS
@@ -93,6 +93,11 @@ GNU coreutils NEWS                                    -*- 
outline -*-
   output.
   [This bug was present in "the beginning".]
 
+  'csplit' no longer fails with a "memory exhausted" error when reading from a
+  pipe or other source that returns short reads, or when reading a long line
+  that requires multiple reads.
+  [This bug was present in "the beginning".]
+
   'cut', 'expand', 'fold', 'join', 'numfmt', 'unexpand', and 'uniq', no longer
   consider the \u0085 (next line) character a separator on non-GLIBC platforms.
   [bug introduced in coreutils-9.11]
diff --git a/src/csplit.c b/src/csplit.c
index 4ab5d9f9f..353741905 100644
--- a/src/csplit.c
+++ b/src/csplit.c
@@ -479,7 +479,19 @@ load_buffer (void)
           hold_count = 0;
         }
 
-      b->bytes_used += read_input (p, bytes_avail - 1);
+      /* Continue reading if we have space and no newlines are found in the
+         current read.  Otherwise, each read without a newline will cause a
+         new allocation in record_line_starts, which can exhaust memory with
+         a slow pipe, for example.  */
+      while (1 < bytes_avail)
+        {
+          idx_t const bytes_read = read_input (p, bytes_avail - 1);
+          b->bytes_used += bytes_read;
+          bytes_avail -= bytes_read;
+          if (bytes_read == 0 || memchr (p, '\n', bytes_read))
+            break;
+          p += bytes_read;
+        }
 
       if (record_line_starts (b) != 0)
         {
diff --git a/tests/csplit/csplit.sh b/tests/csplit/csplit.sh
index b36b83380..2ec08a569 100755
--- a/tests/csplit/csplit.sh
+++ b/tests/csplit/csplit.sh
@@ -180,4 +180,21 @@ if ! uid_is_privileged_; then
   chmod u+w xx00 || framework_failure_
 fi
 
+rm -f xx?? &&
+printf 'a\nb\n' >f || framework_failure_
+vm=$(get_min_ulimit_v_ csplit -z f %b%1) && {
+  printf '0\n50\n' >exp-out &&
+  yes a | tr -d '\n' | head -c 50 > exp-xx01 || framework_failure_
+  (ulimit -v $(($vm + 40000)) && touch ulimit-worked &&
+     for i in $(seq 50); do printf 'a'; sleep .01; done | csplit - 1 >out 
2>err)
+  if test $? -ne 0; then
+    test -f ulimit-worked && fail=1
+  else
+    compare exp-out out || fail=1
+    compare /dev/null err || fail=1
+    compare /dev/null xx00 || fail=1
+    compare exp-xx01 xx01 || fail=1
+  fi
+}
+
 Exit $fail
-- 
2.56.1


Reply via email to