From 06ea5da2c8f9fd93e72223a9bf67e8cd05be4f64 Mon Sep 17 00:00:00 2001 From: Alex Henrie Date: Tue, 20 Jul 2021 13:52:53 -0600 Subject: [PATCH] Fix memory leak on error path in register_select And remove dead error handling code from unregister_select. Closes https://github.com/espressif/esp-idf/pull/7296 --- components/vfs/vfs_uart.c | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/components/vfs/vfs_uart.c b/components/vfs/vfs_uart.c index 706e8d96f8..9f4457c094 100644 --- a/components/vfs/vfs_uart.c +++ b/components/vfs/vfs_uart.c @@ -356,9 +356,11 @@ static esp_err_t register_select(uart_select_args_t *args) if (args) { portENTER_CRITICAL(&s_registered_select_lock); const int new_size = s_registered_select_num + 1; - if ((s_registered_selects = realloc(s_registered_selects, new_size * sizeof(uart_select_args_t *))) == NULL) { + uart_select_args_t **new_selects; + if ((new_selects = realloc(s_registered_selects, new_size * sizeof(uart_select_args_t *))) == NULL) { ret = ESP_ERR_NO_MEM; } else { + s_registered_selects = new_selects; s_registered_selects[s_registered_select_num] = args; s_registered_select_num = new_size; ret = ESP_OK; @@ -382,12 +384,9 @@ static esp_err_t unregister_select(uart_select_args_t *args) // last item. s_registered_selects[i] = s_registered_selects[new_size]; s_registered_selects = realloc(s_registered_selects, new_size * sizeof(uart_select_args_t *)); - if (s_registered_selects || new_size == 0) { - s_registered_select_num = new_size; - ret = ESP_OK; - } else { - ret = ESP_ERR_NO_MEM; - } + // Shrinking a buffer with realloc is guaranteed to succeed. + s_registered_select_num = new_size; + ret = ESP_OK; break; } }