Re: Memory management with C aggregate

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Ian Burrell <imb(at)rentrak(dot)com>
Cc: pgsql-hackers(at)postgresql(dot)org
Subject: Re: Memory management with C aggregate
Date: 2004-07-10 17:00:22
Message-ID: 12847.1089478822@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Ian Burrell <imb(at)rentrak(dot)com> writes:
> We have user-defined aggregates written in C running inside the server.
> We are running into some memory management issues and wondering what
> is the best way to solve the problem.

> The state of the aggregates is a structure with a pointer to allocated
> memory. The structure and memory are allocated in the
> PortalMemoryContext and freed in the ffunc. We just discovered that the
> ffunc function can be called multiple times with the same state on
> certain queries. The double free causes a crash.

AFAICS the ffunc should be called only once per aggregated group.
Perhaps your code is confused about the handling of groups? If so,
the double free is hardly your only worry --- you'll be computing wrong
answers anyway till you fix that.

> From what I could find, the proper way to handle this is let the memory
> be freed when the memory context is freed. What is the right memory
> context to be used to allocate the aggregate state?

I'd use the memory context identified by fcinfo->flinfo->fn_mcxt.

regards, tom lane

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Bruce Momjian 2004-07-10 17:37:59 Re: [BUGS] BUG #1118: Misleading Commit message
Previous Message Tom Lane 2004-07-10 16:48:14 Re: [BUGS] BUG #1118: Misleading Commit message