[PATCH] Add use of asprintf()

From: Peter Eisentraut <peter_e(at)gmx(dot)net>
To: pgsql-hackers <pgsql-hackers(at)postgresql(dot)org>
Subject: [PATCH] Add use of asprintf()
Date: 2013-09-14 02:25:43
Message-ID: 1379125543.19286.17.camel@vanquo.pezone.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

There is a lot of code around that does something like

char *val = malloc(...obscure computation...);
sprintf(val, "...", ...);

This can be had simpler, with asprintf(). It is not standard, but it's
more widely accepted in C libraries than strlcpy for example. The above
code would simply become

char * val;
asprintf(&val, "...", ...);

and asprintf() will figure out how much memory it needs by itself.

The attached patch should speak for itself.

I have supplied a few variants:

- asprintf() is the standard function, supplied by libpgport if
necessary.

- pg_asprintf() is asprintf() with automatic error handling (like
pg_malloc(), etc.)

- psprintf() is the same idea but with palloc.

I didn't touch most places involving MAXPGPATH. There was a discussion
recently about reducing its usage to save memory. That would work well
on top of my patch.

I did some desultory performance testing, which didn't result in any
concerns. Most of the changes are not in performance-critical paths.

If you're very picky you might notice that the psprintf() implementation
asserts that vsnprintf() does not return negative results. Very old
versions of glibc did that (before 2.1/February 1999), and this issue is
referenced in the current code of copy.c (via be4b8a86). But I think
this issue is too ancient now to be of concern.

Attachment Content-Type Size
0001-Add-use-of-asprintf.patch text/x-patch 55.8 KB

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Marko Tiikkaja 2013-09-14 02:58:47 Re: PL/pgSQL, RAISE and error context
Previous Message Kevin Grittner 2013-09-14 02:20:11 Re: record identical operator