Re: Per-thread leak in ECPG's memory.c

From: Heikki Linnakangas <hlinnaka(at)iki(dot)fi>
To: Thomas Munro <thomas(dot)munro(at)gmail(dot)com>, pgsql-hackers <pgsql-hackers(at)postgresql(dot)org>
Subject: Re: Per-thread leak in ECPG's memory.c
Date: 2026-07-06 19:34:59
Message-ID: 9dd704b8-f8f6-4ef2-9971-c9227fc53089@iki.fi
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On 29/06/2026 16:19, Thomas Munro wrote:
> Hi,
>
> ECPG's auto_mem_destructor() doesn't seem quite right:
>
> 1. POSIX thread-specific keys are reset to NULL before their at-exit
> destructors are called, so its call to ECPGfree_auto_mem() gets NULL
> from get_auto_allocs(), so nothing much happens. It should use the
> value passed to the destructor.
>
> 2. ECPGfree_auto_mem() doesn't seem to be the right thing to do
> anyway, because the user is expected to free heap objects allocated by
> the library, for example where
> src/interfaces/ecpg/test/thread/alloc.pgc does this:
>
> char **r = NULL;
> ...
> for (i = 1; i <= REPEATS; ++i)
> {
> EXEC SQL SELECT relname INTO :r FROM pg_class WHERE relname =
> 'pg_class';
> free(r);
> r = NULL;
> }
>
> With a fix for only problem #1 in place, the thread-exit destructor
> double-frees "r" from the final loop. I *think* what is wanted here
> is ecpg_clear_auto_mem(), to free just the list structure and not the
> values themselves. Draft patch like that attached.
>
> It still leaks on Windows, but that's a known issue and I have a fix
> for that as part of a larger refactoring of thread-related stuff, more
> on that shortly. This looked like a bug to report separately first.

Good catch!

I wonder if we should refrain from doing the "set_auto_allocs(NULL);"
call from the destructor. I guess it's harmless, but it feels a bit
wrong to me. Like in the attached.

> Hmm, I wonder why ecpg_raise() frees auto-allocated values for all
> connections just because one connection raised an error.

I didn't look at that

- Heikki

Attachment Content-Type Size
v2-0001-ecpg-Fix-auto_mem-cleanup-on-thread-exit.patch text/x-patch 2.3 KB

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Robert Haas 2026-07-06 19:48:04 Re: Use PG_MODULE_MAGIC_EXT macro in modules added in PG19
Previous Message Robert Haas 2026-07-06 19:32:00 Re: hashjoins vs. Bloom filters (yet again)