Java – JNA memory leak
In view of this, C code:
void LoadData(char** myVar) { std:: string str("[Really Long String Here]"); unsigned int size = str.length() + 1; *myVar = new char[size]; strncpy(*myVar,str.c_str(),size); }
And this JNA Java:
Pointer myVar = new Memory(Pointer.SIZE); this.Lib.LoadData(myVar); this.someVar = myVar.getPointer(0).getString(0);
I have a memory leak. As far as I know, getpointer (0) should create a pointer object that should be released on finalize (), but it doesn't seem to be
Did I miss anything? This seems to meet the specification... I can run the above function without leakage penalty in C
I invoke Java code in a loop to test the leak. I tried to pause and manually call GC, which also expanded to gigabytes at a fairly fast rate.
I've been battling this problem for days, and it's easy to hang up trivial things like trying to free memory As far as I know, if I have an address, I can only release memory manually in Java, but I can't see how I do it
Edit:
It doesn't matter. I even think there is a way to manually pass JNA for free without extending it
Solution
Add this function to the C library
void FreeData(char** myVar) { delete [] *myVar; }
Then use it as JNA code
Pointer myVar = new Memory(Pointer.SIZE); this.Lib.LoadData(myVar); this.someVar = myVar.getPointer(0).getString(0); this.Lib.FreeData(myVar);
In this way, memory can be allocated and deleted in C