From acc80849955f037e9833582decb803cccd0f6126 Mon Sep 17 00:00:00 2001
From: Tristan Partin <tristan@partin.io>
Date: Thu, 12 Nov 2026 19:30:14 +0000
Subject: [PATCH v2 1/2] Add pg_attribute_malloc

The malloc function attribute tells the compiler that the pointer
returned by a function does not alias any other pointer that is valid
when the function returns, and that the storage it addresses contains no
pointers to valid objects. Compilers can optimize callers based on this,
and GCC can also assume that such functions rarely return NULL.

Clang also supports the attribute. A following commit marks the memory
allocation functions with it.

Author: Tristan Partin <tristan@partin.io>
Signed-off-by: Tristan Partin <tristan@partin.io>
---
 src/include/c.h | 15 +++++++++++++++
 1 file changed, 15 insertions(+)

diff --git a/src/include/c.h b/src/include/c.h
index 4bbb0071289..e2c9a6f8824 100644
--- a/src/include/c.h
+++ b/src/include/c.h
@@ -293,6 +293,21 @@ extern "C++"
 #define pg_attribute_no_sanitize_function()
 #endif
 
+/*
+ * pg_attribute_malloc indicates that the function is malloc-like: the
+ * returned pointer does not alias any other pointer valid when the function
+ * returns, and the storage it addresses contains no pointers to valid
+ * objects. GCC can infer that functions marked as malloc also rarely return
+ * NULL.
+ *
+ * https://gcc.gnu.org/onlinedocs/gcc/Common-Attributes.html#index-malloc
+ */
+#if __has_attribute(malloc)
+#define pg_attribute_malloc __attribute__((malloc))
+#else
+#define pg_attribute_malloc
+#endif
+
 /*
  * pg_attribute_nonnull means the compiler should warn if the function is
  * called with the listed arguments set to NULL.  If no arguments are
-- 
Tristan Partin
https://tristan.partin.io

