Report a potential memory leak in setup_config() - Mailing list pgsql-bugs

From wliang@stu.xidian.edu.cn
Subject Report a potential memory leak in setup_config()
Date
Msg-id 64ee7543.20d.17efb1270ca.Coremail.wliang@stu.xidian.edu.cn
Whole thread Raw
Responses Re: Report a potential memory leak in setup_config()  (Daniel Gustafsson <daniel@yesql.se>)
Re: Report a potential memory leak in setup_config()  (wliang@stu.xidian.edu.cn)
List pgsql-bugs
Hi all,

I find a potential memory leak in PostgresSQL 14.1, which is in the function setup_config (./src/bin/initdb/initdb.c).

Specifically, at line 1095, function pretty_wal_size() is called, which allocates a chunk of memory by using pg_malloc and returns it. However, the return chunk is directly passed to snprintf as its 3rd parameter. As a result, there is a memory leak.

1053 static void
1054 setup_config(void)
1055 {
...
1094     snprintf(repltok, sizeof(repltok), "min_wal_size = %s",
1095              pretty_wal_size(DEFAULT_MIN_WAL_SEGS));
...
1347 }

1036 static char *
1037 pretty_wal_size(int segment_count)
1038 {
1039     int         sz = wal_segment_size_mb * segment_count;
1040     char       *result = pg_malloc(14);
1041 
1042     if ((sz % 1024) == 0)
1043         snprintf(result, 14, "%dGB", sz / 1024);
1044     else
1045         snprintf(result, 14, "%dMB", sz);
1046 
1047     return result;
1048 }

We believe we can fix this problem by adding a variable to receive the return of pretty_wal_size() and employing pg_free() to free the leaked memory.

I'm looking forward to your confirmation.

Best,

Wentao

pgsql-bugs by date:

Previous
From: Tom Lane
Date:
Subject: Re: BUG #17391: While using --with-ssl=openssl and PG_TEST_EXTRA='ssl' options, SSL tests fail on OpenBSD 7.0
Next
From: wliang@stu.xidian.edu.cn
Date:
Subject: Report a potential memory leak in describeOneTableDetails()