From 9ac11a752a19c3b8607582a3d5ccb615c467124b Mon Sep 17 00:00:00 2001 From: Benjamin Peterson Date: Sun, 18 Sep 2016 18:00:25 -0700 Subject: [PATCH] properly free memory in pgen --- Include/grammar.h | 1 + Parser/grammar.c | 17 +++++++++++++++++ Parser/pgen.c | 18 ++++++++++++++++-- Parser/pgenmain.c | 1 + 4 files changed, 35 insertions(+), 2 deletions(-) diff --git a/Include/grammar.h b/Include/grammar.h index 85120b9be96..f775f963817 100644 --- a/Include/grammar.h +++ b/Include/grammar.h @@ -69,6 +69,7 @@ typedef struct { /* FUNCTIONS */ grammar *newgrammar(int start); +void freegrammar(grammar *g); dfa *adddfa(grammar *g, int type, const char *name); int addstate(dfa *d); void addarc(dfa *d, int from, int to, int lbl); diff --git a/Parser/grammar.c b/Parser/grammar.c index 84223c66a80..75fd5b9cde5 100644 --- a/Parser/grammar.c +++ b/Parser/grammar.c @@ -28,6 +28,23 @@ newgrammar(int start) return g; } +void +freegrammar(grammar *g) +{ + int i; + for (i = 0; i < g->g_ndfas; i++) { + free(g->g_dfa[i].d_name); + for (int j = 0; j < g->g_dfa[i].d_nstates; j++) + PyObject_FREE(g->g_dfa[i].d_state[j].s_arc); + PyObject_FREE(g->g_dfa[i].d_state); + } + PyObject_FREE(g->g_dfa); + for (i = 0; i < g->g_ll.ll_nlabels; i++) + free(g->g_ll.ll_label[i].lb_str); + PyObject_FREE(g->g_ll.ll_label); + PyObject_FREE(g); +} + dfa * adddfa(grammar *g, int type, const char *name) { diff --git a/Parser/pgen.c b/Parser/pgen.c index be35e02fa56..6451a1d9986 100644 --- a/Parser/pgen.c +++ b/Parser/pgen.c @@ -117,6 +117,16 @@ newnfagrammar(void) return gr; } +static void +freenfagrammar(nfagrammar *gr) +{ + for (int i = 0; i < gr->gr_nnfas; i++) { + PyObject_FREE(gr->gr_nfa[i]->nf_state); + } + PyObject_FREE(gr->gr_nfa); + PyObject_FREE(gr); +} + static nfa * addnfa(nfagrammar *gr, char *name) { @@ -488,7 +498,11 @@ makedfa(nfagrammar *gr, nfa *nf, dfa *d) convert(d, xx_nstates, xx_state); - /* XXX cleanup */ + for (int i = 0; i < xx_nstates; i++) { + for (int j = 0; j < xx_state[i].ss_narcs; j++) + delbitset(xx_state[i].ss_arc[j].sa_bitset); + PyObject_FREE(xx_state[i].ss_arc); + } PyObject_FREE(xx_state); } @@ -669,7 +683,7 @@ pgen(node *n) g = maketables(gr); translatelabels(g); addfirstsets(g); - PyObject_FREE(gr); + freenfagrammar(gr); return g; } diff --git a/Parser/pgenmain.c b/Parser/pgenmain.c index e9d308234b9..e386248c2f8 100644 --- a/Parser/pgenmain.c +++ b/Parser/pgenmain.c @@ -80,6 +80,7 @@ main(int argc, char **argv) printf("Writing %s ...\n", graminit_h); printnonterminals(g, fp); fclose(fp); + freegrammar(g); Py_Exit(0); return 0; /* Make gcc -Wall happy */ }