Skip to content

Commit ebd1887

Browse files
committed
[2.7] properly free memory in pgen.
(cherry picked from commit 9ac11a7) Co-authored-by: Benjamin Peterson <[email protected]>
1 parent 1c9a72c commit ebd1887

File tree

4 files changed

+36
-2
lines changed

4 files changed

+36
-2
lines changed

Include/grammar.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ typedef struct {
6969
/* FUNCTIONS */
7070

7171
grammar *newgrammar(int start);
72+
void freegrammar(grammar *g);
7273
dfa *adddfa(grammar *g, int type, char *name);
7374
int addstate(dfa *d);
7475
void addarc(dfa *d, int from, int to, int lbl);

Parser/grammar.c

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,24 @@ newgrammar(int start)
3232
return g;
3333
}
3434

35+
void
36+
freegrammar(grammar *g)
37+
{
38+
int i;
39+
for (i = 0; i < g->g_ndfas; i++) {
40+
int j;
41+
free(g->g_dfa[i].d_name);
42+
for (j = 0; j < g->g_dfa[i].d_nstates; j++)
43+
PyObject_FREE(g->g_dfa[i].d_state[j].s_arc);
44+
PyObject_FREE(g->g_dfa[i].d_state);
45+
}
46+
PyObject_FREE(g->g_dfa);
47+
for (i = 0; i < g->g_ll.ll_nlabels; i++)
48+
free(g->g_ll.ll_label[i].lb_str);
49+
PyObject_FREE(g->g_ll.ll_label);
50+
PyObject_FREE(g);
51+
}
52+
3553
dfa *
3654
adddfa(grammar *g, int type, char *name)
3755
{

Parser/pgen.c

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,16 @@ newnfagrammar(void)
117117
return gr;
118118
}
119119

120+
static void
121+
freenfagrammar(nfagrammar *gr)
122+
{
123+
for (int i = 0; i < gr->gr_nnfas; i++) {
124+
PyObject_FREE(gr->gr_nfa[i]->nf_state);
125+
}
126+
PyObject_FREE(gr->gr_nfa);
127+
PyObject_FREE(gr);
128+
}
129+
120130
static nfa *
121131
addnfa(nfagrammar *gr, char *name)
122132
{
@@ -488,7 +498,11 @@ makedfa(nfagrammar *gr, nfa *nf, dfa *d)
488498

489499
convert(d, xx_nstates, xx_state);
490500

491-
/* XXX cleanup */
501+
for (int i = 0; i < xx_nstates; i++) {
502+
for (int j = 0; j < xx_state[i].ss_narcs; j++)
503+
delbitset(xx_state[i].ss_arc[j].sa_bitset);
504+
PyObject_FREE(xx_state[i].ss_arc);
505+
}
492506
PyObject_FREE(xx_state);
493507
}
494508

@@ -669,7 +683,7 @@ pgen(node *n)
669683
g = maketables(gr);
670684
translatelabels(g);
671685
addfirstsets(g);
672-
PyObject_FREE(gr);
686+
freenfagrammar(gr);
673687
return g;
674688
}
675689

Parser/pgenmain.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ main(int argc, char **argv)
6767
printf("Writing %s ...\n", graminit_h);
6868
printnonterminals(g, fp);
6969
fclose(fp);
70+
freegrammar(g);
7071
Py_Exit(0);
7172
return 0; /* Make gcc -Wall happy */
7273
}

0 commit comments

Comments
 (0)