Skip to content

Commit b0ae6db

Browse files
committed
psql: Fix memory leak with repeated calls of \bind
Calling \bind repeatedly would cause the memory allocated for the list of bind parameters to be leaked after each call, as the list is reset when beginning a single call. This issue is fixed by making the cleanup of the bind parameter list more aggressive, refactoring it into a single routine called after processing a query and before running an individual \bind. HEAD required more surgery and has been fixed by 87eeada. Issue introduced by 5b66de3. Reported-by: Anthonin Bonnefoy Discussion: https://postgr.es/m/2e5b89af-a351-ff0a-000c-037ac28314ab@gmail.com Backpatch-through: 16
1 parent 19b389c commit b0ae6db

File tree

3 files changed

+23
-9
lines changed

3 files changed

+23
-9
lines changed

src/bin/psql/command.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -471,7 +471,7 @@ exec_command_bind(PsqlScanState scan_state, bool active_branch)
471471
int nparams = 0;
472472
int nalloc = 0;
473473

474-
pset.bind_params = NULL;
474+
clean_bind_state();
475475

476476
while ((opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false)))
477477
{

src/bin/psql/common.c

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1275,14 +1275,7 @@ SendQuery(const char *query)
12751275
}
12761276

12771277
/* clean up after \bind */
1278-
if (pset.bind_flag)
1279-
{
1280-
for (i = 0; i < pset.bind_nparams; i++)
1281-
free(pset.bind_params[i]);
1282-
free(pset.bind_params);
1283-
pset.bind_params = NULL;
1284-
pset.bind_flag = false;
1285-
}
1278+
clean_bind_state();
12861279

12871280
/* reset \gset trigger */
12881281
if (pset.gset_prefix)
@@ -2252,6 +2245,26 @@ uri_prefix_length(const char *connstr)
22522245
return 0;
22532246
}
22542247

2248+
/*
2249+
* Reset state related to \bind
2250+
*
2251+
* Clean up any state related to bind parameters and bind_flag. This needs
2252+
* to be called after processing a query or when running \bind.
2253+
*/
2254+
void
2255+
clean_bind_state(void)
2256+
{
2257+
if (pset.bind_flag)
2258+
{
2259+
for (int i = 0; i < pset.bind_nparams; i++)
2260+
free(pset.bind_params[i]);
2261+
free(pset.bind_params);
2262+
}
2263+
2264+
pset.bind_params = NULL;
2265+
pset.bind_flag = false;
2266+
}
2267+
22552268
/*
22562269
* Recognized connection string either starts with a valid URI prefix or
22572270
* contains a "=" in it.

src/bin/psql/common.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ extern bool standard_strings(void);
4141
extern const char *session_username(void);
4242

4343
extern void expand_tilde(char **filename);
44+
extern void clean_bind_state(void);
4445

4546
extern bool recognized_connection_string(const char *connstr);
4647

0 commit comments

Comments
 (0)