Fix memory leaks from incorrect strsep() uses
authorPeter Eisentraut <peter@eisentraut.org>
Fri, 18 Oct 2024 09:28:54 +0000 (11:28 +0200)
committerPeter Eisentraut <peter@eisentraut.org>
Fri, 18 Oct 2024 09:29:20 +0000 (11:29 +0200)
Commit 5d2e1cc117b introduced some strsep() uses, but it did the
memory management wrong in some cases.  We need to keep a separate
pointer to the allocate memory so that we can free it later, because
strsep() advances the pointer we pass to it, and it at the end it
will be NULL, so any free() calls won't do anything.

(This fixes two of the four places changed in commit 5d2e1cc117b.  The
other two don't have this problem.)

Reported-by: Alexander Lakhin <exclusion@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/79692bf9-17d3-41e6-b9c9-fc8c3944222a@eisentraut.org

src/common/logging.c
src/test/regress/pg_regress.c

index aedd1ae2d8c12c4825cac7440820f5787abb47d6..3cf119090a5d35ee9606aaadde573c30f92689fe 100644 (file)
@@ -120,8 +120,9 @@ pg_logging_init(const char *argv0)
                        if (colors)
                        {
                                char       *token;
+                               char       *cp = colors;
 
-                               while ((token = strsep(&colors, ":")))
+                               while ((token = strsep(&cp, ":")))
                                {
                                        char       *e = strchr(token, '=');
 
index 5157629b1cc2fc2be7e409cdcedf74ee76807390..6c188954b142ac4ae29800638b5ea7513db650c7 100644 (file)
@@ -233,14 +233,17 @@ free_stringlist(_stringlist **listhead)
 static void
 split_to_stringlist(const char *s, const char *delim, _stringlist **listhead)
 {
-       char       *sc = pg_strdup(s);
        char       *token;
+       char       *sc;
+       char       *tofree;
+
+       tofree = sc = pg_strdup(s);
 
        while ((token = strsep(&sc, delim)))
        {
                add_stringlist_item(listhead, token);
        }
-       free(sc);
+       free(tofree);
 }
 
 /*