JNI内存泄漏

============问题描述============



jboolean

Java_com_test_Image_isImageFormat(JNIEnv* env, jobject obj, jstring path)

{

    FILE *fis = NULL;

    jboolean ret = JNI_FALSE;

    unsigned short pis[128];

    char cString[256];



    const char *fileName = (*env)->GetStringUTFChars(env, path, 0);



    char *p = strrchr(fileName, '.');

    if(p == NULL)

    {

    	(*env)->ReleaseStringUTFChars(env, path, fileName);

    	return JNI_FALSE;

    }



    short int i = 0;

    char *q  = p;

    for(i = 0; i < strlen(q); i++)

    	*(q+i) = tolower(*(q+i));



    strcpy(cString, fileName);



    (*env)->ReleaseStringUTFChars(env, path, fileName);



    if((fis=fopen(cString, "r"))==NULL)

    {

    	__android_log_print(ANDROID_LOG_ERROR, "isImageFormat", "=============Can not open the file==================");

    	fclose(fis);

    	return JNI_FALSE;

    }



    fread(pis, 8, 1, fis);

.

.

.

}


首先要说的是,这函数会被频繁调用;
而这段代码常报内存泄漏,但是实在找不出哪里导致的内存没有释放啊!懂的人帮忙看看!

============解决方案1============


函数不全,怎么知道有没有内存泄漏呢。
fis这个句柄后面有关闭吗?

另外有几个问题:
1.strlen重复调用,效率很低。

for(i = 0; i < strlen(q); i++)

        *(q+i) = tolower(*(q+i));


2.没有字符串长度检查,可能导致内存写越界。

strcpy(cString, fileName);

============解决方案2============



if((fis=fopen(cString, "r"))==NULL)

    {

        __android_log_print(ANDROID_LOG_ERROR, "isImageFormat", "=============Can not open the file==================");

        fclose(fis);

        return JNI_FALSE;

    }

LZ都知道是这段代码出错了!很明显文件都没有打开成功,却去做关闭文件句柄的操作。。能不报错吗?
原文地址:https://www.cnblogs.com/lianxu61/p/4046134.html