Re: Weird problems with C extension and bytea as input type

From: Adrian Schreyer <ams214(at)cam(dot)ac(dot)uk>
To: Merlin Moncure <mmoncure(at)gmail(dot)com>
Cc: dennis jenkins <dennis(dot)jenkins(dot)75(at)gmail(dot)com>, pgsql-general(at)postgresql(dot)org
Subject: Re: Weird problems with C extension and bytea as input type
Date: 2011-03-23 15:33:59
Message-ID: AANLkTim5vu7fek6w8kTGwyi1CFZmgBqO5Zm2ty8rnFi1@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Wed, Mar 23, 2011 at 14:08, Merlin Moncure <mmoncure(at)gmail(dot)com> wrote:
> On Wed, Mar 23, 2011 at 9:04 AM, dennis jenkins
> <dennis(dot)jenkins(dot)75(at)gmail(dot)com> wrote:
>> On Wed, Mar 23, 2011 at 5:08 AM, Adrian Schreyer <ams214(at)cam(dot)ac(dot)uk> wrote:
>>>
>>> you are right, it returns a char *.
>>>
>>> The prototype:
>>>
>>> char *function(bytea *b);
>>>
>>> The actual C++ function looks roughly like this
>>>
>>> extern "C"
>>> char *function(bytea *b)
>>> {
>>>   string ism;
>>>   [...]
>>>   return ism.c_str();
>>> }
>>>
>>
>>
>> Don't do that.  You are returning a pointer to an unallocated buffer
>> (previously held by a local variable).  c_str() is just a const
>> pointer to a buffer held inside "ism".  When ism goes out of scope,
>> that buffer if freed.
>>
>> Either return "std::string", or strdup() the string and have the
>> caller free that.  (but use the postgresql alloc pool function to
>> handle the strdup.  I don't recall that function's name off the top of
>> my head).
>
> that would be pstrdup, and it's the way to go (you don't have to
> pfree).  who says C doesn't have garbage collection?
>
> merlin
>
> --
> Sent via pgsql-general mailing list (pgsql-general(at)postgresql(dot)org)
> To make changes to your subscription:
> http://www.postgresql.org/mailpref/pgsql-general
>
I am using pstrdup and it works now as expected. Thank you all for your help,

Adrian

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2011-03-23 16:42:42 Re: Recursive function that receives a list of IDs and returns all child IDs
Previous Message Adrian Schreyer 2011-03-23 15:32:58 Re: Weird problems with C extension and bytea as input type