Re: Exception Handling in C-Language Functions?

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: "Felix E(dot) Klee" <felix(dot)klee(at)inka(dot)de>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Exception Handling in C-Language Functions?
Date: 2005-05-21 14:30:47
Message-ID: 9274.1116685847@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

"Felix E. Klee" <felix(dot)klee(at)inka(dot)de> writes:
> I have the created a C-Language function (code is below). Now, I
> wonder: How do I handle exceptions, for example if malloc cannot assign
> the necessary memory? Do "palloc" and "pfree" handle such a case
> cleanly? Should I simply use an "assert"?

As a general rule, never ever use malloc in backend code --- there's way
too much risk of causing a memory leak. (If your function for some
reason errors out before reaching the free(), that memory is gone.
Lather, rinse, repeat a few million times, as is not unlikely to happen
in a database server, and you've got a big problem.)

Use palloc instead. You don't have to check it for a failure return,
as Neil already noted, and you can be sloppy about remembering to free
the result ... in fact, there's no real reason to free it at all, since
anything palloc gives you inside a function will be short-term memory.
See src/backend/utils/mmgr/README for details.

If you want to report your own errors, use elog/ereport.

BTW, a more future-proof way of doing what you want:

> VarChar *text = PG_GETARG_VARCHAR_P(0);
> int text_len = VARSIZE(text)-VARHDRSZ;
> char *tmp_text = (char *)malloc(text_len+1);
> if (tmp_text == NULL)
> ; /* What now? */
> strncpy(tmp_text, VARDATA(text), text_len);
> tmp_text[text_len] = '\0';

is to let the varchar output routine do it:

Datum text_datum = PG_GETARG_DATUM(0);
char *text;

text = DatumGetCString(DirectFunctionCall1(varcharout, text_datum));

This avoids assuming that you know the internal representation of
varchar (and if you think that's frozen for eternity, you haven't
been reading the discussions of ramping up our locale support...)

regards, tom lane

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Jim C. Nasby 2005-05-21 18:14:43 Re: table synonyms
Previous Message Martijn van Oosterhout 2005-05-21 11:43:26 Re: numeric precision when raising one numeric to another.