Skip to content

Commit a39331f

Browse files
committed
Fix low-probability memory leak in regex execution.
After an internal failure in shortest() or longest() while pinning down the exact location of a match, find() forgot to free the DFA structure before returning. This is pretty unlikely to occur, since we just successfully ran the "search" variant of the DFA; but it could happen, and it would result in a session-lifespan memory leak since this code uses malloc() directly. Problem seems to have been aboriginal in Spencer's library, so back-patch all the way. In passing, correct a thinko in a comment I added awhile back about the meaning of the "ntree" field. I happened across these issues while comparing our code to Tcl's version of the library.
1 parent e8e2999 commit a39331f

File tree

3 files changed

+7
-3
lines changed

3 files changed

+7
-3
lines changed

src/backend/regex/regcomp.c

+1-1
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,7 @@ struct vars
228228
struct subre *tree; /* subexpression tree */
229229
struct subre *treechain; /* all tree nodes allocated */
230230
struct subre *treefree; /* any free tree nodes */
231-
int ntree; /* number of tree nodes */
231+
int ntree; /* number of tree nodes, plus one */
232232
struct cvec *cv; /* interface cvec */
233233
struct cvec *cv2; /* utility cvec */
234234
struct subre *lacons; /* lookahead-constraint vector */

src/backend/regex/regexec.c

+5-1
Original file line numberDiff line numberDiff line change
@@ -348,7 +348,11 @@ find(struct vars * v,
348348
(chr **) NULL, &hitend);
349349
else
350350
end = longest(v, d, begin, v->stop, &hitend);
351-
NOERR();
351+
if (ISERR())
352+
{
353+
freedfa(d);
354+
return v->err;
355+
}
352356
if (hitend && cold == NULL)
353357
cold = begin;
354358
if (end != NULL)

src/include/regex/regguts.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -470,7 +470,7 @@ struct guts
470470
size_t nsub; /* copy of re_nsub */
471471
struct subre *tree;
472472
struct cnfa search; /* for fast preliminary search */
473-
int ntree; /* number of subre's, less one */
473+
int ntree; /* number of subre's, plus one */
474474
struct colormap cmap;
475475
int FUNCPTR(compare, (const chr *, const chr *, size_t));
476476
struct subre *lacons; /* lookahead-constraint vector */

0 commit comments

Comments
 (0)