Re: C function woes

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Chris Hayner <hayner80(at)astro(dot)ocis(dot)temple(dot)edu>
Cc: PostgreSQL-General <pgsql-general(at)postgresql(dot)org>
Subject: Re: C function woes
Date: 2001-02-20 22:52:23
Message-ID: 6943.982709543@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Chris Hayner <hayner80(at)astro(dot)ocis(dot)temple(dot)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

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2001-02-20 22:56:30 Re: C function woes
Previous Message Chris Hayner 2001-02-20 21:56:53 C function woes (more info)