Re: Pointer subtraction with a null pointer - Mailing list pgsql-hackers

From Tom Lane
Subject Re: Pointer subtraction with a null pointer
Date
Msg-id 103098.1648318436@sss.pgh.pa.us
Whole thread Raw
In response to Re: Pointer subtraction with a null pointer  (Andres Freund <andres@anarazel.de>)
Responses Re: Pointer subtraction with a null pointer
List pgsql-hackers
Andres Freund <andres@anarazel.de> writes:
> Wonder if we should try to get rid of the problem by also fixing the double
> evaluation of val? I think something like

Good idea.  The attached also silences the warning, and getting rid
of the double-eval hazard seems like a net win.

> Might also be worth adding an assertion that base < val.

Did that too.  On the whole I like this better.

            regards, tom lane

diff --git a/src/include/utils/relptr.h b/src/include/utils/relptr.h
index fdc2124d2c..cc80a7200d 100644
--- a/src/include/utils/relptr.h
+++ b/src/include/utils/relptr.h
@@ -56,11 +56,24 @@
 #define relptr_is_null(rp) \
     ((rp).relptr_off == 0)
 
+/* We use this inline to avoid double eval of "val" in relptr_store */
+static inline Size
+relptr_store_eval(char *base, char *val)
+{
+    if (val == NULL)
+        return 0;
+    else
+    {
+        Assert(val > base);
+        return val - base;
+    }
+}
+
 #ifdef HAVE__BUILTIN_TYPES_COMPATIBLE_P
 #define relptr_store(base, rp, val) \
     (AssertVariableIsOfTypeMacro(base, char *), \
      AssertVariableIsOfTypeMacro(val, __typeof__((rp).relptr_type)), \
-     (rp).relptr_off = ((val) == NULL ? 0 : ((char *) (val)) - (base)))
+     (rp).relptr_off = relptr_store_eval(base, (char *) (val)))
 #else
 /*
  * If we don't have __builtin_types_compatible_p, assume we might not have
@@ -68,7 +81,7 @@
  */
 #define relptr_store(base, rp, val) \
     (AssertVariableIsOfTypeMacro(base, char *), \
-     (rp).relptr_off = ((val) == NULL ? 0 : ((char *) (val)) - (base)))
+     (rp).relptr_off = relptr_store_eval(base, (char *) (val)))
 #endif
 
 #define relptr_copy(rp1, rp2) \

pgsql-hackers by date:

Previous
From: Andres Freund
Date:
Subject: Re: Pointer subtraction with a null pointer
Next
From: Tomas Vondra
Date:
Subject: Re: Column Filtering in Logical Replication