BUG/MEDIUM: pattern: fixup use_after_free in the pat_ref_delete_by_id

I found there is use_after_free bug in the pat_ref_delete_by_id.

[wt: it seems this fix must be backported to 1.5 as well]

(cherry picked from commit aede6ddd1f3a9ad553bc17eba9b0b1d09094b3ca)
diff --git a/src/pattern.c b/src/pattern.c
index b19ffe2..5817f7e 100644
--- a/src/pattern.c
+++ b/src/pattern.c
@@ -1423,14 +1423,13 @@
 	/* delete pattern from reference */
 	list_for_each_entry_safe(elt, safe, &ref->head, list) {
 		if (elt == refelt) {
+			list_for_each_entry(expr, &ref->pat, list)
+				pattern_delete(expr, elt);
+
 			LIST_DEL(&elt->list);
 			free(elt->sample);
 			free(elt->pattern);
 			free(elt);
-
-			list_for_each_entry(expr, &ref->pat, list)
-				pattern_delete(expr, elt);
-
 			return 1;
 		}
 	}