PATCH: Fun fact: mbsrtowcs() does not nul terminate the string

Mikael Magnusson <[email protected]>
Newsgroups gmane.comp.shells.zsh.devel
Message-ID <[email protected]>
---
This caused a few unpredictable bugs and problems, and also a metric
truckload of warnings from valgrind. Oops.

 Src/utils.c | 12 ++++++++----
 1 file changed, 8 insertions(+), 4 deletions(-)

diff --git a/Src/utils.c b/Src/utils.c
index 869accccdd..7499298ab5 100644
--- a/Src/utils.c
+++ b/Src/utils.c
@@ -4760,11 +4760,12 @@ set_keylayout(UNUSED(Param pm), char *x)
 	wmemset(&newkeymap[10*15], L'\n', 15);
 	newkeymap[165] = L'\0';
 	int line;
-	int xlen;
+	int xlen, wxlen;
 	unmetafy(x, &xlen);
 	wchar_t *wx = zalloc(sizeof(wchar_t) * (xlen + 1)), *wxp = wx;
 	const char *xr = x;
-	mbsrtowcs(wx, &xr, xlen, &mbs);
+	wxlen = mbsrtowcs(wx, &xr, xlen, &mbs);
+	wx[wxlen] = L'\0';
 
 	wchar_t *p = wx;
 	const size_t pos[] = { 15 + 2, 15*2 + 2, 15*3 + 2, 15*4 + 1, 15*6 + 2, 15*7 + 2, 15*8 + 2, 15*9 + 1 };
@@ -4811,10 +4812,13 @@ spdist(char *s, char *t, int thresh)
     mbstate_t mbs;
     wchar_t *wsp = ws, *wtp = wt;
 
+    int wslen, wtlen;
     memset(&mbs, 0, sizeof(mbs));
-    mbsrtowcs(ws, (const char**)&s, slen, &mbs);
+    wslen = mbsrtowcs(ws, (const char**)&s, slen, &mbs);
     memset(&mbs, 0, sizeof(mbs));
-    mbsrtowcs(wt, (const char**)&t, tlen, &mbs);
+    wtlen = mbsrtowcs(wt, (const char**)&t, tlen, &mbs);
+    ws[wslen] = L'\0';
+    wt[wtlen] = L'\0';
 
     int result = wcspdist(ws, wt, thresh);
     zfree(ws, sizeof(wchar_t) * (slen + 1));
-- 
2.38.1
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.