Re: Consistently use palloc_object() and palloc_array()

Tom Lane <tgl@sss.pgh.pa.us>

From: Tom Lane <tgl@sss.pgh.pa.us>
To: David Geier <geidav.pg@gmail.com>
Cc: Chao Li <li.evan.chao@gmail.com>, pgsql-hackers <pgsql-hackers@postgresql.org>
Date: 2025-11-28T21:28:43Z
Lists: pgsql-hackers

Commits

Same data as JSON: GET /api/v1/messages/:b64id/commits the thread's linked commits as JSON, with link sources. API reference →
  1. btree_gist: Fix memory allocation formula

  2. Use palloc_object() and palloc_array(), the last change

  3. pg_buffercache: Fix memory allocation formula

  4. Fix allocation formula in llvmjit_expr.c

  5. Use palloc_object() and palloc_array() in backend code

  6. Use palloc_object() and palloc_array() in more areas of the tree

  7. Use more palloc_object() and palloc_array() in contrib/

David Geier <geidav.pg@gmail.com> writes:
> On 27.11.2025 00:03, Chao Li wrote:
>> This is a large patch, I just take a quick look, and found that:
>> -		*phoned_word = palloc(sizeof(char) * strlen(word) + 1);
>> +		*phoned_word = palloc_array(char, strlen(word) + 1);
>> And
>> -		params = (const char **) palloc(sizeof(char *));
>> +		params = palloc_object(const char *);
>> Applying palloc_array and palloc_object to char type doesn’t seem to improve anything.

> You mean because sizeof(char) is always 1 and hence we could instead
> simply write:
> 		*phoned_word = palloc(strlen(word) + 1);
> 		params = palloc(1);
> I think the _array and _object variants are more expressive and for sure
> don't make the code less readable.

Yeah, I agree these particular changes seem fine.  When you're doing
address arithmetic for a memcpy or such, it may be fine to wire in an
assumption that sizeof(char) == 1, but I think doing that in other
contexts is not particularly good style.

Another thing to note is that the proposed patch effectively changes
the expression evaluation order:

-		*phoned_word = palloc((sizeof(char) * strlen(word)) + 1);
+		*phoned_word = palloc(sizeof(char) * (strlen(word) + 1));

Now, there's not actually any difference because sizeof(char) is 1,
but if it hypothetically weren't, the new version is likely more
correct.  Presumably the +1 is meant to allow room for a trailing \0,
which is a char.

It'd be a good idea to review the patch to see if there are any
places where semantics are changed in a less benign fashion...

			regards, tom lane