From fb4940f784df1cbae7dec5c96ba0d2de3f58dbb9 Mon Sep 17 00:00:00 2001
From: Eli Collins <eli@cloudera.com>
Date: Tue, 19 Jan 2010 18:38:36 -0800
Subject: [PATCH] HDFS-464: Memory leaks in libhdfs

---
 src/c++/libhdfs/hdfs.c          |   15 ++++++++++-----
 src/c++/libhdfs/hdfsJniHelper.c |    1 +
 2 files changed, 11 insertions(+), 5 deletions(-)

diff --git a/src/c++/libhdfs/hdfs.c b/src/c++/libhdfs/hdfs.c
index 6289804..b84fef7 100644
--- a/src/c++/libhdfs/hdfs.c
+++ b/src/c++/libhdfs/hdfs.c
@@ -262,12 +262,14 @@ hdfsFS hdfsConnectAsUser(const char* host, tPort port, const char *user , const
           destroyLocalReference(env, jGroups);
         }          
         destroyLocalReference(env, jUgi);
+        destroyLocalReference(env, jAttrString);
         return NULL;
       }
 
       destroyLocalReference(env, jUserString);
       destroyLocalReference(env, jGroups);
       destroyLocalReference(env, jUgi);
+      destroyLocalReference(env, jAttrString);
     }
 #else
     
@@ -448,12 +450,14 @@ hdfsFS hdfsConnectAsUserNewInstance(const char* host, tPort port, const char *us
           destroyLocalReference(env, jGroups);
         }          
         destroyLocalReference(env, jUgi);
+        destroyLocalReference(env, jAttrString);
         return NULL;
       }
 
       destroyLocalReference(env, jUserString);
       destroyLocalReference(env, jGroups);
       destroyLocalReference(env, jUgi);
+      destroyLocalReference(env, jAttrString);
     }
 #else
     
@@ -732,12 +736,12 @@ hdfsFile hdfsOpenFile(hdfsFS fs, const char* path, int flags,
     file = malloc(sizeof(struct hdfsFile_internal));
     if (!file) {
         errno = ENOMEM;
-        return NULL;
-    }
-    file->file = (*env)->NewGlobalRef(env, jVal.l);
-    file->type = (((flags & O_WRONLY) == 0) ? INPUT : OUTPUT);
+    } else {
+        file->file = (*env)->NewGlobalRef(env, jVal.l);
+        file->type = (((flags & O_WRONLY) == 0) ? INPUT : OUTPUT);
 
-    destroyLocalReference(env, jVal.l);
+        destroyLocalReference(env, jVal.l);
+    }
 
     done:
 
@@ -1655,6 +1659,7 @@ int hdfsChmod(hdfsFS fs, const char* path, short mode)
     //Create an object of org.apache.hadoop.fs.Path
     jobject jPath = constructNewObjectOfPath(env, path);
     if (jPath == NULL) {
+      destroyLocalReference(env, jPermObj);
       return -3;
     }
 
diff --git a/src/c++/libhdfs/hdfsJniHelper.c b/src/c++/libhdfs/hdfsJniHelper.c
index ea0fa88..f5ab81b 100644
--- a/src/c++/libhdfs/hdfsJniHelper.c
+++ b/src/c++/libhdfs/hdfsJniHelper.c
@@ -242,6 +242,7 @@ jarray constructNewArrayString(JNIEnv *env, Exc *exc, const char **elements, int
       fprintf(stderr, "ERROR: jelem == NULL\n");
     }
     (*env)->SetObjectArrayElement(env, result, i, jelem);
+    (*env)->DeleteLocalRef(env, jelem);
   }
   return result;
 }
-- 
1.6.0.4

