Fix mismatched deallocation functions

From: "Tristan Partin" <tristan(at)partin(dot)io>
To: "pgsql-hackers" <pgsql-hackers(at)postgresql(dot)org>
Subject: Fix mismatched deallocation functions
Date: 2026-05-06 23:26:42
Message-ID: DIBZE2B6SVF2.28R3EQTYJSWIG@partin.io
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

In fe_memutils.h, we have two sets of allocation/deallocation functions:
those that start pg_ and those that start with p. pg_malloc vs palloc,
pg_free vs pfree, etc. My understanding is that we probably want to
match the allocator with the deallocator whenever possible, but that is
not the case in HEAD. We have quite a few mismatches.

I discovered these issues when adding some __attribute__((malloc))
annotations to our allocation functions. gcc presents warnings in the
form of:

../src/bin/psql/tab-complete.in.c: In function ‘psql_completion’:
../src/bin/psql/tab-complete.in.c:2143:9: warning: ‘free’ called on pointer returned from a mismatched allocation function [-Wmismatched-dealloc]
2143 | free(text_copy);
| ^~~~~~~~~~~~~~~
../src/bin/psql/tab-complete.in.c:1971:33: note: returned from ‘pnstrdup’
1971 | char *text_copy = pnstrdup(rl_line_buffer + start, end - start);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Memory that we allocated pnstrdup() is being deallocated with free().
In actuality, this is not an issue because pnstrdup() uses malloc()
internally. However, it does create a little bit of mental overhead when
analyzing memory management in code paths. Warnings like this are also
a barrier to annotating our memory allocation functions with
__attribute__((malloc)).

The supplied patch allows for a clean compliation on my Linux x86_64
machine with malloc attribute applied. I will send that patch later
after a little bit more development.

I generated the patch with the help of Coccinelle[0]. I'm no expert with
Coccinelle, but it seemed like a good candidate to get this refactor
done. You can run the attached script in your tree with the following
command:

spatch --sp-file allocators.cocci --allow-inconsistent-paths \
--in-place .

[0]: https://coccinelle.gitlabpages.inria.fr/website/

--
Tristan Partin
PostgreSQL Contributors Team
AWS (https://aws.amazon.com)

Attachment Content-Type Size
v1-0001-Fix-mismatched-deallocation-functions.patch text/x-patch 48.7 KB
allocators.cocci text/plain 4.7 KB

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Melanie Plageman 2026-05-06 23:54:36 Re: [PATCH] pg_surgery: Fix WAL corruption from concurrent heap_force_kill
Previous Message Michael Paquier 2026-05-06 23:22:49 Re: Fix DROP PROPERTY GRAPH "unsupported object class" error