diff --git a/libasn1compiler/asn1c_naming.c b/libasn1compiler/asn1c_naming.c
index 223fa6d973158f50526ddc41655369099ba29448..122e1f798a789ed83b5c116a765879c0556aea5d 100644
--- a/libasn1compiler/asn1c_naming.c
+++ b/libasn1compiler/asn1c_naming.c
@@ -17,6 +17,24 @@ c_name_clash_finder_init() {
     TQ_INIT(&used_names);
 }
 
+void
+c_name_clash_finder_destroy() {
+    struct intl_name *n;
+
+    while((n = TQ_REMOVE(&used_names, next))) {
+        union {
+            const char *c_buf;
+            char *nc_buf;
+        } const_cast;
+
+        asn1p_expr_free(n->expr);
+        asn1p_expr_free(n->clashes_with);
+        const_cast.c_buf = n->name;
+        free(const_cast.nc_buf);
+        free(n);
+    }
+}
+
 static void
 register_global_name(arg_t *arg, const char *name) {
     struct intl_name *n;
@@ -25,14 +43,19 @@ register_global_name(arg_t *arg, const char *name) {
         if(strcmp(n->name, name) == 0) {
             if(!(arg->expr->_mark & TM_NAMEGIVEN) && arg->expr != n->expr) {
                 n->clashes_with = arg->expr;
+                arg->expr->ref_cnt++;
                 return;
             }
         }
     }
 
+    if(arg->expr->_mark & TM_NAMEGIVEN)
+        return;
+
     n = calloc(1, sizeof(*n));
     assert(n);
     n->expr = arg->expr;
+    arg->expr->ref_cnt++;
     n->name = strdup(name);
     TQ_ADD(&used_names, n, next);
 }
diff --git a/libasn1compiler/asn1c_naming.h b/libasn1compiler/asn1c_naming.h
index 737f1339fb22e211e5c8a1c6ec4b51d0728b7feb..40825609203a07f9f3c6559406f4ed0a3de693e7 100644
--- a/libasn1compiler/asn1c_naming.h
+++ b/libasn1compiler/asn1c_naming.h
@@ -25,4 +25,6 @@ int c_name_clash(arg_t *arg);
 
 void c_name_clash_finder_init(void);
 
+void c_name_clash_finder_destroy(void);
+
 #endif	/* ASN1_COMPILER_NAMING_H */
diff --git a/libasn1compiler/asn1compiler.c b/libasn1compiler/asn1compiler.c
index 8d963ef67e8906efb2c380562a9f4032bf52aeb1..056b9dda21966e92249e70ded0c27d4818aa0c08 100644
--- a/libasn1compiler/asn1compiler.c
+++ b/libasn1compiler/asn1compiler.c
@@ -79,6 +79,8 @@ asn1_compile(asn1p_t *asn, const char *datadir, enum asn1c_flags flags,
 
 	DEBUG("Saving compiled data");
 
+	c_name_clash_finder_destroy();
+
 	/*
 	 * Save or print out the compiled result.
 	 */