From b9adfc5f91f56ebabbef4fc85fef92608209bb21 Mon Sep 17 00:00:00 2001 From: "Bi-Ruei, Chiu" Date: Wed, 9 Nov 2016 00:17:25 +0800 Subject: [PATCH] Free memory allocated in various functions 1. Add 'ref_cnt' field to asn1p_expr_t. 2. Initialize 'ref_cnt' field to zero when asn1p_expr_t is allocated. 3. Increase 'ref_cnt' field when asn1p_expr_t is cloned by asn1p_value_fromtype(). 4. If 'ref_cnt' field of asn1p_expr_t is larger than zero, then asn1p_expr_free() only decrease its value. 5. Free memory pointed by fields of asn1p_expr_t and itself when 'ref_cnt' is zero and asn1p_expr_free() called. 6. Call asn1p_delete(asn) in main(). --- asn1c/asn1c.c | 2 ++ libasn1parser/asn1p_expr.c | 7 +++++++ libasn1parser/asn1p_expr.h | 1 + libasn1parser/asn1p_value.c | 2 ++ 4 files changed, 12 insertions(+) diff --git a/asn1c/asn1c.c b/asn1c/asn1c.c index 8a6f785e..2f5194c6 100644 --- a/asn1c/asn1c.c +++ b/asn1c/asn1c.c @@ -330,6 +330,8 @@ main(int ac, char **av) { exit(EX_SOFTWARE); } + asn1p_delete(asn); + return 0; } diff --git a/libasn1parser/asn1p_expr.c b/libasn1parser/asn1p_expr.c index b7a03ecb..c2261e67 100644 --- a/libasn1parser/asn1p_expr.c +++ b/libasn1parser/asn1p_expr.c @@ -22,6 +22,7 @@ asn1p_expr_new(int _lineno, asn1p_module_t *mod) { expr->spec_index = -1; expr->module = mod; expr->_lineno = _lineno; + expr->ref_cnt = 0; } return expr; @@ -235,6 +236,12 @@ asn1p_expr_free(asn1p_expr_t *expr) { if(expr) { asn1p_expr_t *tm; + if (expr->ref_cnt) { + /* Decrease reference count only */ + expr->ref_cnt--; + return; + } + /* Remove all children */ while((tm = TQ_REMOVE(&(expr->members), next))) { if(tm->parent_expr != expr) diff --git a/libasn1parser/asn1p_expr.h b/libasn1parser/asn1p_expr.h index 89d939a0..dfeaa25d 100644 --- a/libasn1parser/asn1p_expr.h +++ b/libasn1parser/asn1p_expr.h @@ -216,6 +216,7 @@ typedef struct asn1p_expr_s { asn1p_value_t *default_value; /* For EM_DEFAULT case */ } marker; int unique; /* UNIQUE */ + int ref_cnt; /* reference count */ /* * Whether automatic tagging may be applied for subtypes. diff --git a/libasn1parser/asn1p_value.c b/libasn1parser/asn1p_value.c index 63c80c7e..0c898880 100644 --- a/libasn1parser/asn1p_value.c +++ b/libasn1parser/asn1p_value.c @@ -138,6 +138,7 @@ asn1p_value_fromtype(asn1p_expr_t *expr) { if(v) { v->value.v_type = expr; v->type = ATV_TYPE; + expr->ref_cnt++; } return v; } @@ -258,6 +259,7 @@ asn1p_value_free(asn1p_value_t *v) { asn1p_value_free(v->value.choice_identifier.value); break; } + memset(v, 0, sizeof(*v)); free(v); } }