| From: | Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us> | 
|---|---|
| To: | Yessica Brinkmann <yessica(dot)brinkmann(at)gmail(dot)com> | 
| Cc: | pgsql-novice(at)lists(dot)postgresql(dot)org | 
| Subject: | Re: CurrentMemoryContext and MemoryContextStrdup | 
| Date: | 2019-11-26 18:11:00 | 
| Message-ID: | 9190.1574791860@sss.pgh.pa.us | 
| Views: | Whole Thread | Raw Message | Download mbox | Resend email | 
| Thread: | |
| Lists: | pgsql-novice | 
Yessica Brinkmann <yessica(dot)brinkmann(at)gmail(dot)com> writes:
> Now, as I understand it (I don't know if I'm right), what I would have to
> do would be this:
> 1. I save the CurrentMemoryContext, for example as follows:
> MemoryContext oldcontext = CurrentMemoryContext;
> 2. I make the call to SPI, which was what caused the context problem.
> 3. I copy my variable in a different context, for example as follows:
> MemoryContext newcontext;
> char * copy = MemoryContextStrdup (newcontext, data);
> 4. Then, at the end of my call to SPI, after SPI_finish () I would have in
> the copy variable, the copy of the data variable, to use it as I want.
> Is that so? I am correct at least to try to modify my program or is it
> totally something else what should I do?
IIRC, the real issue here is that SPI_connect creates and switches into
a temporary context that SPI_finish will destroy; and the string you want
is in that short-lived context.  So what you want is to copy it out of
that context, probably into the context that was current before you
call SPI_connect.  So what you want is to do this before calling
SPI_connect:
MemoryContext outer_context = CurrentMemoryContext;
and then this, inside the SPI operation, will save your string safely:
copy = MemoryContextStrdup(outer_context, data);
regards, tom lane
| From | Date | Subject | |
|---|---|---|---|
| Next Message | Yessica Brinkmann | 2019-11-26 18:20:15 | Re: CurrentMemoryContext and MemoryContextStrdup | 
| Previous Message | Yessica Brinkmann | 2019-11-26 17:34:32 | Re: CurrentMemoryContext and MemoryContextStrdup |