Re: Exception Handling in C-Language Functions?

From: Merlin Moncure <mmoncure(at)gmail(dot)com>
To: rahul143 <rk204885(at)gmail(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Exception Handling in C-Language Functions?
Date: 2012-12-03 14:42:48
Message-ID: CAHyXU0wSbZp3gdtm__LU+rGYs4JxdM84o+1rx=ytyYayymP_2Q@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general pgsql-www

On Sun, Dec 2, 2012 at 11:18 PM, rahul143 <rk204885(at)gmail(dot)com> wrote:
> 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"?
>
> #include "postgres.h"
> #include <string.h>
> #include <stdlib.h>
> #include "fmgr.h"
> #include "libinn.h"
>
> PG_FUNCTION_INFO_V1(ffiinews_uwildmat);
>
> /* Wrapper for INN's function uwildmat. Needs parameters in UTF-8. */
> Datum ffiinews_uwildmat(PG_FUNCTION_ARGS) {
> VarChar *text = PG_GETARG_VARCHAR_P(0);
> VarChar *pattern = PG_GETARG_VARCHAR_P(1);
> int text_len = VARSIZE(text)-VARHDRSZ;
> int pattern_len = VARSIZE(pattern)-VARHDRSZ;
> char *tmp_text = (char *)malloc(text_len+1);
> if (tmp_text == NULL)
> ; /* What now? */
> char *tmp_pattern = (char *)malloc(pattern_len+1);
> if (tmp_pattern == NULL)
> ; /* What now? */
> strncpy(tmp_text, VARDATA(text), text_len);
> tmp_text[text_len] = '\0';
> strncpy(tmp_pattern, VARDATA(pattern), pattern_len);
> tmp_pattern[pattern_len] = '\0';
> bool matches = uwildmat(tmp_text, tmp_pattern);

yes, you should always use database memory api: palloc/pfree and if
necessary memory context switching. memory allocation error then
raises database exception. any situation that raises an exception or
other critical needs to be caught and rethrown as database exception
(ereport, etc).

merlin

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Alvaro Herrera 2012-12-03 14:57:47 Re: High SYS CPU - need advise
Previous Message Merlin Moncure 2012-12-03 14:36:38 Re: High SYS CPU - need advise

Browse pgsql-www by date

  From Date Subject
Next Message Peter Eisentraut 2012-12-04 11:51:49 Re: Re: [BUGS] BUG #6639: Manual uses boldface where it says italic, and monospace where it says boldface
Previous Message David Fetter 2012-12-03 13:38:50 Re: MODERATOR WARNING Re: [GENERAL] Exception Handling in C-Language Functions?