schema compile UPDATE use refcount for leafref realtypes
diff --git a/src/schema_compile.c b/src/schema_compile.c
index b72d8d2..58d458a 100644
--- a/src/schema_compile.c
+++ b/src/schema_compile.c
@@ -1134,9 +1134,10 @@
         }
     }
 
-    /* store the target's type and check for circular chain of leafrefs */
-    lref->realtype = ((struct lysc_node_leaf *)target)->type;
-    for (type = lref->realtype; type && type->basetype == LY_TYPE_LEAFREF; type = ((struct lysc_type_leafref *)type)->realtype) {
+    /* check for circular chain of leafrefs */
+    for (type = ((struct lysc_node_leaf *)target)->type;
+            type && (type->basetype == LY_TYPE_LEAFREF);
+            type = ((struct lysc_type_leafref *)type)->realtype) {
         if (type == (struct lysc_type *)lref) {
             /* circular chain detected */
             LOGVAL(ctx->ctx, LYVE_REFERENCE, "Invalid leafref path \"%s\" - circular chain of leafrefs detected.",
@@ -1145,6 +1146,9 @@
         }
     }
 
+    /* store the type */
+    lref->realtype = ((struct lysc_node_leaf *)target)->type;
+    ++lref->realtype->refcount;
     return LY_SUCCESS;
 }
 
@@ -1414,7 +1418,10 @@
             for (typeiter = lref->realtype;
                     typeiter->basetype == LY_TYPE_LEAFREF;
                     typeiter = ((struct lysc_type_leafref *)typeiter)->realtype) {}
+
+            lysc_type_free(ctx, lref->realtype);
             lref->realtype = typeiter;
+            ++lref->realtype->refcount;
         }
 
         /* If 'goto' will be used on the 'resolve_all' label, then
diff --git a/src/tree_schema_free.c b/src/tree_schema_free.c
index c6fa656..2a95c75 100644
--- a/src/tree_schema_free.c
+++ b/src/tree_schema_free.c
@@ -749,7 +749,7 @@
 void
 lysc_type_free(struct ly_ctx *ctx, struct lysc_type *type)
 {
-    if (LY_ATOMIC_DEC_BARRIER(type->refcount) > 1) {
+    if (!type || (LY_ATOMIC_DEC_BARRIER(type->refcount) > 1)) {
         return;
     }
 
@@ -789,6 +789,7 @@
     case LY_TYPE_LEAFREF:
         lyxp_expr_free(ctx, ((struct lysc_type_leafref *)type)->path);
         ly_free_prefix_data(LY_VALUE_SCHEMA_RESOLVED, ((struct lysc_type_leafref *)type)->prefixes);
+        lysc_type_free(ctx, ((struct lysc_type_leafref *)type)->realtype);
         break;
     case LY_TYPE_INST:
     case LY_TYPE_BOOL: