[PATCH 1/1] rev: handle cases where lines are too long for buffer

Clayton Craft clayton at craftyguy.net
Mon Aug 9 19:25:33 UTC 2021


This fixes a problem where the contents of the previous line were output
when the previous line was long enough to cause buf to be extended.
The buffer is re-used/rewritten for each line, instead of appending to it.
---
 util-linux/rev.c | 13 +++++++------
 1 file changed, 7 insertions(+), 6 deletions(-)

diff --git a/util-linux/rev.c b/util-linux/rev.c
index d439b4da8..53b6b91aa 100644
--- a/util-linux/rev.c
+++ b/util-linux/rev.c
@@ -78,20 +78,21 @@ int rev_main(int argc UNUSED_PARAM, char **argv)
 		pos = 0;
 		while (1) {
 			/* Read one line */
-			buf[bufsize - 1] = 1; /* not 0 */
-			if (!fgets(buf + pos, bufsize - pos, fp))
+			if (!fgets(buf, bufsize, fp))
 				break; /* EOF/error */
-			if (buf[bufsize - 1] == '\0' /* fgets filled entire buffer */
-			 && buf[bufsize - 2] != '\n' /* and did not read '\n' */
+			int len = strlen(buf);
+			while (buf[len - 1] != '\n' /* fgets filled entire buffer */
 			 && !feof(fp)
 			) {
 				/* Line is too long, extend buffer */
 				pos = bufsize - 1;
 				bufsize += 64 + bufsize / 8;
 				buf = xrealloc(buf, bufsize);
-				continue;
+				/* Fill remaining buffer */
+				if (!fgets(buf + pos, bufsize - pos, fp))
+					break;
+				len = strlen(buf);
 			}
-
 			/* Process and print it */
 #if ENABLE_UNICODE_SUPPORT
 			{
-- 
2.32.0



More information about the busybox mailing list