Skip to content

Commit ead70a8

Browse files
committed
jni: avoid memory leaks
Signed-off-by: Alexander Bezzubov <[email protected]>
1 parent 9d6d5bf commit ead70a8

File tree

2 files changed

+11
-6
lines changed

2 files changed

+11
-6
lines changed

src/main/native/org_bblfsh_client_v2_libuast_Libuast.cc

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -633,7 +633,7 @@ Java_org_bblfsh_client_v2_libuast_Libuast_00024UastIter_nativeInit(
633633
}
634634

635635
// global ref will be deleted by Interface destructor on ctx deletion
636-
auto it = ctx->Iterate(env->NewGlobalRef(jnode), (TreeOrder)order);
636+
auto it = ctx->Iterate(jnode, (TreeOrder)order);
637637

638638
// this.iter = it;
639639
setHandle<uast::Iterator<Node *>>(env, self, it, "iter");
@@ -754,8 +754,7 @@ JNIEXPORT jobject JNICALL Java_org_bblfsh_client_v2_Context_filter(
754754

755755
uast::Iterator<Node *> *it = nullptr;
756756
try {
757-
// global ref will be deleted by Interface destructor on ctx deletion
758-
it = ctx->Filter(env->NewGlobalRef(jnode), query);
757+
it = ctx->Filter(jnode, query);
759758
} catch (const std::exception &e) {
760759
ThrowByName(env, CLS_RE, e.what());
761760
return nullptr;
@@ -819,8 +818,10 @@ JNIEXPORT jobject JNICALL Java_org_bblfsh_client_v2_ContextExt_encode(
819818
JNIEXPORT void JNICALL
820819
Java_org_bblfsh_client_v2_ContextExt_dispose(JNIEnv *env, jobject self) {
821820
ContextExt *p = getHandle<ContextExt>(env, self, nativeContext);
822-
setHandle<ContextExt>(env, self, 0, nativeContext);
823-
delete p;
821+
if (!p) {
822+
delete p;
823+
setHandle<ContextExt>(env, self, 0, nativeContext);
824+
}
824825
}
825826

826827
// ==========================================

src/test/scala/org/bblfsh/client/v2/libuast/IteratorManagedTest.scala

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ class IteratorManagedTest extends FlatSpec
1919
))
2020

2121
after {
22-
iter.nativeDispose() // FIXME: rename to .dispose()
22+
iter.close()
2323
}
2424

2525
"Managed UAST iterator" should "return non-empty results on JVM objects" in {
@@ -77,6 +77,8 @@ class IteratorManagedTest extends FlatSpec
7777
val poActual = Seq("root", "son1", "son1_1", "son1_2", "son2", "son2_1", "son2_2")
7878
nodes should have size (poActual.size)
7979
nodes shouldEqual poActual
80+
81+
preIter.close()
8082
}
8183

8284
"Managed UAST iterator" should "return nodes in PostOrder" in {
@@ -86,6 +88,8 @@ class IteratorManagedTest extends FlatSpec
8688
val poActual = Seq("son1_1", "son1_2", "son1", "son2_1", "son2_2", "son2", "root")
8789
nodes should have size (poActual.size)
8890
nodes shouldEqual poActual
91+
92+
postIter.close()
8993
}
9094

9195
// TODO(#108) more tests coverage for other iteration orders, refactor to a table-driven test

0 commit comments

Comments
 (0)