Backport of:

From 82ba55b8f994ab30ff561a347b82ea340ba7075c Mon Sep 17 00:00:00 2001
From: "Thomas E. Dickey" <dickey@invisible-island.net>
Date: Tue, 9 Feb 2021 23:04:41 +0000
Subject: [PATCH] snapshot of project "xterm", label xterm-365d

---
 MANIFEST       |  2 +-
 button.c       | 25 ++++++++++++++++++++-----
 xterm.log.html |  5 ++++-
 3 files changed, 25 insertions(+), 7 deletions(-)

#diff --git a/MANIFEST b/MANIFEST
#index 47e1318..3ed1c73 100644
#--- a/MANIFEST
#+++ b/MANIFEST
#@@ -1,4 +1,4 @@
#-MANIFEST for xterm, version xterm-365c
#+MANIFEST for xterm, version xterm-365d
# --------------------------------------------------------------------------------
# MANIFEST                        this file
# 256colres.h                     resource-definitions for 256-color mode
--- a/button.c
+++ b/button.c
@@ -4198,6 +4198,7 @@ SaltTextAway(XtermWidget xw,
     int i;
     int eol;
     int need = 0;
+    size_t have = 0;
     Char *line;
     Char *lp;
     CELL first = *cellc;
@@ -4232,7 +4233,11 @@ SaltTextAway(XtermWidget xw,
 
     /* UTF-8 may require more space */
     if_OPT_WIDE_CHARS(screen, {
-	need *= 4;
+	if (need > 0) {
+	    if (screen->max_combining > 0)
+		need += screen->max_combining;
+	    need *= 6;
+	}
     });
 
     /* now get some memory to save it in */
@@ -4270,10 +4275,20 @@ SaltTextAway(XtermWidget xw,
     }
     *lp = '\0';			/* make sure we have end marked */
 
-    TRACE(("Salted TEXT:%u:%s\n", (unsigned) (lp - line),
-	   visibleChars(line, (unsigned) (lp - line))));
+    have = (size_t) (lp - line);
+    /*
+     * Scanning the buffer twice is unnecessary.  Discard unwanted memory if
+     * the estimate is too-far off.
+     */
+    if ((have * 2) < (size_t) need) {
+	scp->data_limit = have + 1;
+	line = realloc(line, scp->data_limit);
+    }
+
+    TRACE(("Salted TEXT:%u:%s\n", (unsigned) have,
+	   visibleChars(line, (unsigned) have)));
 
-    scp->data_length = (size_t) (lp - line);
+    scp->data_length = have;
 }
 
 #if OPT_PASTE64
