D Liebman
D Liebman

Reputation: 347

C memory leak in android JNI code

I have an app that uses android jni. In java I do something like this:

setTilemapData( a, b, c, d);

a,b,c and d are arrays that contain bitmap information that my c code displays on the egl 1.0 screen. The function setTilemapData() is a native function in my Panel class. That works fine.

First in c I do something like this:

static uint16_t tiles_a[16][16];
static uint16_t tiles_b[16][16];
static uint16_t tiles_c[16][16];
static uint16_t tiles_d[16][16];

Then, somewhere:

JNIEXPORT void JNICALL Java_some_package_Panel_setTileMapData(JNIEnv * env, jobject  obj, jintArray a_bitmap, jintArray b_bitmap, jintArray c_bitmap, jintArray d_bitmap)
{

    jint *a = (*env)->GetIntArrayElements(env, a_bitmap, 0);

    jint *b = (*env)->GetIntArrayElements(env, b_bitmap, 0);

    jint *c = (*env)->GetIntArrayElements(env, c_bitmap, 0);

    jint *d = (*env)->GetIntArrayElements(env, d_bitmap, 0);
    setTileMapData(a, b, c, d );

    (*env)->ReleaseIntArrayElements(env, a_bitmap,a,NULL);
    (*env)->ReleaseIntArrayElements(env, b_bitmap,b,NULL);
    (*env)->ReleaseIntArrayElements(env, c_bitmap,c,NULL);
    (*env)->ReleaseIntArrayElements(env, d_bitmap,d,NULL);
}


void setTileMapData(jint a[], jint b[], jint c[], jint d[] ) {


    copyArraysExpand(a, TILEMAP_WIDTH * TILEMAP_HEIGHT, tiles_a);
    copyArraysExpand(b, TILEMAP_WIDTH * TILEMAP_HEIGHT, tiles_b);
    copyArraysExpand(c, TILEMAP_WIDTH * TILEMAP_HEIGHT, tiles_c);
    copyArraysExpand(d, TILEMAP_WIDTH * TILEMAP_HEIGHT, tiles_d);

}

void copyArraysExpand (jint from[], int size_l, uint16_t to[TILEMAP_HEIGHT][TILEMAP_WIDTH]) {

    int num, n, l;
    int i,j, k;
    for (i = 0; i< TILEMAP_HEIGHT; i ++ ) {
        for (j = 0; j < TILEMAP_WIDTH; j ++ ) {
            k =( i * TILEMAP_WIDTH ) + j;
            if ( k < size_l ) {

                to[i][j] = ( from[k]);
            }
        }
    }

    return;
}

//Later I use the data in tiles_a as a pattern which I copy to the screen (almost like a sprite or something)

Somewhere in all of this there is a horrible memory leak. I have tried to malloc space and assign it to tiles_a, so that later I can free it, but the ide complains that it is an array and cannot be assigned to in that way.

The app actually runs on many devices, but will crash after some repetition of the setTilemapData code.

EDIT: I've updated this listing some.

Upvotes: 0

Views: 231

Answers (1)

Gabe Sechan
Gabe Sechan

Reputation: 93569

You aren't ever releasing the arrays from Java. You need to call ReleaseIntArrayElements after copying the data- after setTileMapData in the main jni function would be easiest.

Upvotes: 2

Related Questions