From 70b4e7948fc82dcf554d3fecfe98e575d00dffa4 Mon Sep 17 00:00:00 2001 From: Axel Date: Mon, 23 Jun 2025 16:07:52 +0200 Subject: [PATCH] fix(tui): avoid memory leak and compiler warning on Windows (#34225) Problem: On Windows, the value of `term` is overwritten without freeing the old allocated value, which may lead to a memory leak. GCC also gives a "incompatible pointer type" warning about passing `*term` to os_tty_guess_term(). Solution: Don't override the old allocated value, and copy the guessed value to `term` if its old value is NULL. (cherry picked from commit fb5a51e77570ce2b548d22d250d503102aeac2fe) --- src/nvim/os/env.c | 3 --- src/nvim/tui/tui.c | 10 ++++++---- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/src/nvim/os/env.c b/src/nvim/os/env.c index 3126881266..21da64a1ee 100644 --- a/src/nvim/os/env.c +++ b/src/nvim/os/env.c @@ -127,9 +127,6 @@ bool os_env_exists(const char *name) /// Sets an environment variable. /// /// Windows (Vim-compat): Empty string (:let $FOO="") undefines the env var. -/// -/// @warning Existing pointers to the result of os_getenv("foo") are -/// INVALID after os_setenv("foo", …). int os_setenv(const char *name, const char *value, int overwrite) FUNC_ATTR_NONNULL_ALL { diff --git a/src/nvim/tui/tui.c b/src/nvim/tui/tui.c index bb91b5336a..91bb65898c 100644 --- a/src/nvim/tui/tui.c +++ b/src/nvim/tui/tui.c @@ -387,10 +387,12 @@ static void terminfo_start(TUIData *tui) const char *term = os_getenv("TERM"); #ifdef MSWIN - os_tty_guess_term(&term, tui->out_fd); - os_setenv("TERM", term, 1); - // Old os_getenv() pointer is invalid after os_setenv(), fetch it again. - term = os_getenv("TERM"); + const char *guessed_term = NULL; + os_tty_guess_term(&guessed_term, tui->out_fd); + if (term == NULL && guessed_term != NULL) { + term = xstrdup(guessed_term); + os_setenv("TERM", guessed_term, 1); + } #endif // Set up unibilium/terminfo.