patch 9.1.1339: missing out-of-memory checks for enc_to_utf16()/utf16_to_enc()

Problem:  missing out-of-memory checks for enc_to_utf16() and
          utf16_to_enc()
Solution: Add out-of-memory checks and fix a few other minor issues
          (John Marriott)

This change does:
-  add missing out-of-memory checks for enc_to_utf16() and
   utf16_to_enc()
-  add a small optimisation in mch_errmsg_c() and mch_msg_c() (in
   message.c) to only call STRLEN() if needed.
-  fix a memory leak in winpty_term_and_job_init() (in terminal.c).

closes: #17191

Signed-off-by: John Marriott <basilisk@internode.on.net>
Signed-off-by: Christian Brabandt <cb@256bit.org>
diff --git a/src/message.c b/src/message.c
index 99fe675..eade461 100644
--- a/src/message.c
+++ b/src/message.c
@@ -3508,7 +3508,6 @@
     static void
 mch_errmsg_c(char *str)
 {
-    int	    len = (int)STRLEN(str);
     DWORD   nwrite = 0;
     DWORD   mode = 0;
     HANDLE  h = GetStdHandle(STD_ERROR_HANDLE);
@@ -3516,10 +3515,14 @@
     if (GetConsoleMode(h, &mode) && enc_codepage >= 0
 	    && (int)GetConsoleCP() != enc_codepage)
     {
+	int	len = (int)STRLEN(str);
 	WCHAR	*w = enc_to_utf16((char_u *)str, &len);
 
-	WriteConsoleW(h, w, len, &nwrite, NULL);
-	vim_free(w);
+	if (w != NULL)
+	{
+	    WriteConsoleW(h, w, len, &nwrite, NULL);
+	    vim_free(w);
+	}
     }
     else
     {
@@ -3614,19 +3617,21 @@
     static void
 mch_msg_c(char *str)
 {
-    int	    len = (int)STRLEN(str);
     DWORD   nwrite = 0;
     DWORD   mode;
     HANDLE  h = GetStdHandle(STD_OUTPUT_HANDLE);
 
-
     if (GetConsoleMode(h, &mode) && enc_codepage >= 0
 	    && (int)GetConsoleCP() != enc_codepage)
     {
+	int	len = (int)STRLEN(str);
 	WCHAR	*w = enc_to_utf16((char_u *)str, &len);
 
-	WriteConsoleW(h, w, len, &nwrite, NULL);
-	vim_free(w);
+	if (w != NULL)
+	{
+	    WriteConsoleW(h, w, len, &nwrite, NULL);
+	    vim_free(w);
+	}
     }
     else
     {