@@ -461,11 +461,10 @@ class Interface : public uast::NodeCreator<Node *> {
461
461
}
462
462
463
463
// toJ returns a JVM object associated with a node.
464
+ // It borrows the reference
464
465
jobject toJ (Node *node) {
465
466
if (!node) return nullptr ;
466
- // TODO(#113) investigate, it looks like a potential memory leak
467
- jobject obj = getJNIEnv ()->NewGlobalRef (node->obj );
468
- return obj;
467
+ return node->obj ;
469
468
}
470
469
471
470
// abstract methods from NodeCreator
@@ -509,7 +508,7 @@ class Interface : public uast::NodeCreator<Node *> {
509
508
};
510
509
511
510
// toJ returns a JVM object associated with a node.
512
- // Returns a new reference.
511
+ // Returns a borrowed reference.
513
512
jobject Node::toJ () { return iface->toJ (this ); }
514
513
515
514
// lookupOrCreate either creates a new object or returns existing one.
@@ -523,7 +522,7 @@ class Context {
523
522
uast::Context<Node *> *ctx;
524
523
525
524
// toJ returns a JVM object associated with a node.
526
- // Returns a new reference.
525
+ // Borrows the reference.
527
526
jobject toJ (Node *node) {
528
527
if (!node) return nullptr ;
529
528
return iface->toJ (node);
@@ -548,10 +547,10 @@ class Context {
548
547
}
549
548
550
549
// RootNode returns a root UAST node, if set.
551
- // Returns a new reference.
550
+ // Returns a borrowed ref
552
551
jobject RootNode () {
553
552
Node *root = ctx->RootNode ();
554
- return toJ (root); // new ref
553
+ return toJ (root); // borrowed ref
555
554
}
556
555
557
556
// Iterate returns iterator over an external UAST tree.
@@ -853,8 +852,14 @@ JNIEXPORT jobject JNICALL Java_org_bblfsh_client_v2_NodeExt_load(JNIEnv *env,
853
852
jobject self) {
854
853
auto ctx = new Context ();
855
854
jobject node = ctx->LoadFrom (self);
855
+ // We need to make a local reference to node since ctx is going to be destroyed
856
+ // before returning, and the global references that each Node carries with it.
857
+ // If we do not copy node in a local ref, we return a null, whereas copying it in
858
+ // a local ref ensures the native part returns the value to Java and after that
859
+ // disposes of the local refs
860
+ jobject result = getJNIEnv ()->NewLocalRef (node);
856
861
delete (ctx);
857
- return node ;
862
+ return result ;
858
863
}
859
864
860
865
JNIEXPORT jobject JNICALL Java_org_bblfsh_client_v2_NodeExt_filter (
0 commit comments