From 4aacf57da1e41643fa789d3ffe848d50029a62de Mon Sep 17 00:00:00 2001
From: Karel Zak <kzak@redhat.com>
Date: Thu, 4 Aug 2022 10:10:19 +0200
Subject: [PATCH] column: fix buffer overflow when -l specified
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

$ printf 'a b c\n1 2 3\n' | column -s : -t -o '-' -l2
a b c-ġ
1 2 3-

Signed-off-by: Karel Zak <kzak@redhat.com>

---
 text-utils/column.c | 14 ++++++++++----
 1 file changed, 10 insertions(+), 4 deletions(-)

diff --git a/text-utils/column.c b/text-utils/column.c
index a4ba24dcd..3d068b08d 100644
--- a/text-utils/column.c
+++ b/text-utils/column.c
@@ -507,17 +507,23 @@ static void modify_table(struct column_control *ctl)
 static int add_line_to_table(struct column_control *ctl, wchar_t *wcs0)
 {
 	wchar_t *wcdata, *sv = NULL, *wcs = wcs0;
-	size_t n = 0, nchars = 0;
+	size_t n = 0, nchars = 0, len;
 	struct libscols_line *ln = NULL;
 
 	if (!ctl->tab)
 		init_table(ctl);
+
+	len = wcslen(wcs0);
+
 	do {
 		char *data;
 
-		if (ctl->maxncols && n + 1 == ctl->maxncols)
-			wcdata = wcs0 + nchars;
-		else
+		if (ctl->maxncols && n + 1 == ctl->maxncols) {
+			if (nchars < len)
+				wcdata = wcs0 + nchars;
+			else
+				wcdata = NULL;
+		} else
 			wcdata = local_wcstok(ctl, wcs, &sv);
 
 		if (!wcdata)
-- 
2.33.0

