From 206388b19eb3e1d98ee77821a96705c97c86eb06 Mon Sep 17 00:00:00 2001 From: Peter Zhu Date: Fri, 12 Jan 2024 15:32:24 -0500 Subject: [PATCH] Fix ruby_free_proctitle It is undefined behaviour to free environ as it is managed by the system. This caused RUBY_FREE_AT_EXIT to double free on systems like Linux. This commit changes it to only free orig_environ, which is enough to make both Valgrind and macOS leaks tools to not detect memory leaks. --- missing/setproctitle.c | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/missing/setproctitle.c b/missing/setproctitle.c index d718123802..f90886671c 100644 --- a/missing/setproctitle.c +++ b/missing/setproctitle.c @@ -153,18 +153,16 @@ ruby_free_proctitle(void) if (!orig_environ) return; /* environ is allocated by OS */ - for (int i = 0; environ[i] != NULL; i++) { - xfree(environ[i]); - } - - /* ruby_setenv could allocate a new environ, so we need to free both environ - * orig_environ in that case. */ + /* ruby_setenv could allocate a new environ, so we need to free orig_environ + * in that case. */ if (environ != orig_environ) { + for (int i = 0; orig_environ[i] != NULL; i++) { + xfree(orig_environ[i]); + } + xfree(orig_environ); orig_environ = NULL; } - - xfree(environ); #endif }