From 73983bada50feb2bf9bb6b6beb99eb243f7c12cc Mon Sep 17 00:00:00 2001 From: Mahmoud Al-Qudsi Date: Mon, 1 May 2023 12:04:26 -0500 Subject: [PATCH] Fix ncurses memory leak in init_curses() init_curses() is/can be called more than once, in which case the previous ncurses terminal state is leaked and a new one is allocated. `del_curterm(cur_term)` is supposed to be called prior to calling `setupterm()` if `setupterm()` is being used to reinit the default `TERMINAL *cur_term`. --- src/env_dispatch.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/env_dispatch.cpp b/src/env_dispatch.cpp index ee4a3636a..9e4be10ba 100644 --- a/src/env_dispatch.cpp +++ b/src/env_dispatch.cpp @@ -565,6 +565,15 @@ static bool does_term_support_setting_title(const environment_t &vars) { return true; } +extern "C" { +void env_cleanup() { + if (cur_term != nullptr) { + del_curterm(cur_term); + cur_term = nullptr; + } +} +} + /// Initialize the curses subsystem. static void init_curses(const environment_t &vars) { for (const auto &var_name : curses_variables) { @@ -580,6 +589,10 @@ static void init_curses(const environment_t &vars) { } } + // init_curses() is called more than once, which can lead to a memory leak if the previous + // ncurses TERMINAL isn't freed before initializing it again with `setupterm()`. + env_cleanup(); + int err_ret{0}; if (setupterm(nullptr, STDOUT_FILENO, &err_ret) == ERR) { if (is_interactive_session()) {