Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1lEvwn-00087U-8j for pgsql-bugs@arkaria.postgresql.org; Wed, 24 Feb 2021 15:19:29 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1lEvwm-0001H0-44 for pgsql-bugs@arkaria.postgresql.org; Wed, 24 Feb 2021 15:19:28 +0000 Received: from makus.postgresql.org ([2001:4800:3e1:1::229]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1lEvwl-0001Gt-Tw for pgsql-bugs@lists.postgresql.org; Wed, 24 Feb 2021 15:19:27 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by makus.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1lEvwj-0007dB-PU for pgsql-bugs@lists.postgresql.org; Wed, 24 Feb 2021 15:19:26 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.15.2/8.15.2) with ESMTP id 11OFJN7O4057244; Wed, 24 Feb 2021 10:19:23 -0500 From: Tom Lane To: Michael Paquier cc: Alexander Lakhin , pgsql-bugs@lists.postgresql.org Subject: Re: BUG #16801: Invalid memory access on WITH RECURSIVE with nested WITHs In-reply-to: References: <16801-393c7922143eaa4d@postgresql.org> Comments: In-reply-to Michael Paquier message dated "Wed, 24 Feb 2021 14:03:40 +0900" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <4057242.1614179963.1@sss.pgh.pa.us> Date: Wed, 24 Feb 2021 10:19:23 -0500 Message-ID: <4057243.1614179963@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk Michael Paquier writes: > So attached is a patch to take care of this, with a regression test > based on what has been sent upthread. This solves the issue for me. Surely that breaks things entirely (if it doesn't, then we are badly under-testing this area). A nil list is just a null pointer, so appending to "new_cte_list" later isn't going to affect what was previously put into the innerwiths list. I haven't tested, but I think a more correct fix would be - ListCell *cell1; cstate->innerwiths = lcons(NIL, cstate->innerwiths); - cell1 = list_head(cstate->innerwiths); foreach(lc, stmt->withClause->ctes) { CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc); + ListCell *cell1; (void) makeDependencyGraphWalker(cte->ctequery, cstate); + /* note innerwiths list can change during recursion */ + cell1 = list_head(cstate->innerwiths); lfirst(cell1) = lappend((List *) lfirst(cell1), cte); } ie, recompute the "cell1" pointer each time it's needed instead of assuming that the original value is good throughout the loop. regards, tom lane