Path: csiph.com!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Rainer Weikusat Newsgroups: comp.databases.postgresql Subject: Re: Anyone here do anything with libpq? Date: Tue, 16 May 2017 20:52:41 +0100 Lines: 41 Message-ID: <87r2zo8tpy.fsf@doppelsaurus.mobileactivedefense.com> References: <871srq6sfx.fsf@doppelsaurus.mobileactivedefense.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-Trace: individual.net HWtFYgYj9quQTq+T030pVAp4+rfujNT41ihvm3CNh7mz1n0ks= Cancel-Lock: sha1:two6RZMJkCsALTrIfDPNhWZd2UY= sha1:gIuw4NmP0rAfhS1jHfZ4mhd+2/4= User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.4 (gnu/linux) Xref: csiph.com comp.databases.postgresql:776 DFS writes: > On 5/15/2017 11:38 AM, Rainer Weikusat wrote: >> DFS writes: >>> https://www.postgresql.org/docs/9.6/static/libpq.html >>> >>> >>> PQclear >>> Frees the storage associated with a PGresult. Every command result >>> should be freed via PQclear when it is no longer needed. >>> >>> void PQclear(PGresult *res); >>> >>> You can keep a PGresult object around for as long as you need it; it >>> does not go away when you issue a new command, nor even if you close >>> the connection. To get rid of it, you must call PQclear. Failure to do >>> this will result in memory leaks in your application. >>> >>> >>> 'when it is no longer needed' sounds like it can be cleared once, at >>> the end of the script. >> >> There seems to be some kind of fundamental misunderstanding about the >> nature of 'a result set' here. Specifically, >> >> PGresult *res; >> >> is a C pointer to a PGresult (structure) and in order to avoid memory >> leaks, the result this pointer points to has to be freed before the >> pointer is overwritten aka reused. >> >> There's no need to free the result if the pointer won't be reused, IOW, >> if the application is going to end next, anyway. > > The question is, if I use a PGresult 10x during a program, should I > clear it between each use, or is one clear at the end OK? Well, you can't do this (as I already wrote): Queries return pointers to result objects, not result objects. And if you overwrite a pointer variable (type PGresult *) pointing to the last result with a pointer to the next result, the old result will be leaked.