relcache: Avoid memory leak on tables with no CHECK constraints
authorÁlvaro Herrera <[email protected]>
Sun, 11 May 2025 13:22:12 +0000 (09:22 -0400)
committerÁlvaro Herrera <[email protected]>
Sun, 11 May 2025 13:22:12 +0000 (09:22 -0400)
As complained about by Valgrind, in commit a379061a22a8 I failed to
realize that I was causing rd_att->constr->check to become allocated
when no CHECK constraints exist; previously it'd remain NULL.  (This was
my bug, not the mentioned commit author's).  Fix by making the
allocation conditional, and set ->check to NULL if unallocated.

Reported-by: Yasir <[email protected]>
Reviewed-by: Tom Lane <[email protected]>
Discussion: https://postgr.es/m/202505082025[email protected]

src/backend/utils/cache/relcache.c

index 68ff67de549acc3b25e850c24b90878c9b16f01e..559ba9cdb2cdedf4aa37c7a97645ecbdaa0c269f 100644 (file)
@@ -4598,10 +4598,13 @@ CheckNNConstraintFetch(Relation relation)
    HeapTuple   htup;
    int         found = 0;
 
-   /* Allocate array with room for as many entries as expected */
-   check = (ConstrCheck *)
-       MemoryContextAllocZero(CacheMemoryContext,
-                              ncheck * sizeof(ConstrCheck));
+   /* Allocate array with room for as many entries as expected, if needed */
+   if (ncheck > 0)
+       check = (ConstrCheck *)
+           MemoryContextAllocZero(CacheMemoryContext,
+                                  ncheck * sizeof(ConstrCheck));
+   else
+       check = NULL;
 
    /* Search pg_constraint for relevant entries */
    ScanKeyInit(&skey[0],