Re: C function woes - Mailing list pgsql-general

From Tom Lane
Subject Re: C function woes
Date
Msg-id 6943.982709543@sss.pgh.pa.us
Whole thread Raw
In response to C function woes  (Chris Hayner <hayner80@astro.ocis.temple.edu>)
Responses Re: C function woes  (Tom Lane <tgl@sss.pgh.pa.us>)
Re: C function woes  (Peter Eisentraut <peter_e@gmx.net>)
List pgsql-general
Chris Hayner <hayner80@astro.ocis.temple.edu> writes:
> text *
> hello()
>  {
>         char data[] = "hello world";
>         int32 new_text_size = VARHDRSZ + sizeof(data);
>         text *new_text = (text *) palloc(new_text_size);

>         strcpy(VARDATA(new_text), data);
>         return new_text;
>  }


You forgot to set the size word of the new text object.  Also, the
strcpy() looks dangerous since it will copy data[]'s trailing null,
which you do not want and did not allocate room for.  In short:

text *
hello()
 {
        char data[] = "hello world";
        int32 new_text_size = VARHDRSZ + sizeof(data);
        text *new_text = (text *) palloc(new_text_size);

    VARSIZE(new_text) = new_text_size;
        memcpy(VARDATA(new_text), data, sizeof(data));
        return new_text;
 }

            regards, tom lane

pgsql-general by date:

Previous
From: Chris Hayner
Date:
Subject: C function woes (more info)
Next
From: Marko Kreen
Date:
Subject: Re: C function woes (more info)