JNA Error at Program Exit
So I have the following in c++
__declspec(dllexport) extern "C"
char** get_prop_types( int* count ) {
const vector<string>& r = prop_manager::get_prop_types();
char **p = (char**)malloc( r.size() );
char **ptr = p;
for( vector<string>::const_iterator it = r.begin(); it!=r.end() ; ++it ) {
*p = (char*)malloc( it->size() );
strcpy(*p++,it->c_str());
}
*count = r.size();
return ptr;
}
and in java
public interface Arch extends Library {
public Pointer get_prop_types( IntByReference size );
}
static Arch theLib; //initialization not shown
public static String[] getPropTypes() {
IntByReference size = new IntByReference();
Pointer strs = theLib.get_prop_types(size);
//free is apparently handled for us?
return strs.getStringArray(0, size.getValue());
}
public static void main( String[] args ) {
System.out.println( Arrays.toString(getPropTypes()) );
}
The above will print out a list of Strings. So far so good. But after main returns (during finalization?) I get an error along the lines of
The instruction at "%08X" referenced memory at "%08x". The memory could not be "read".
I get the same error when trying to ma开发者_高级运维nually free()
the char**
or each individual char*
Can someone tell me what I've done wrong? Or at least point we to some more resources?
This:
*p = (char*)malloc( it->size() );
should be:
*p = (char*)malloc( it->size() + 1);
And I just noticed that:
char **p = (char**)malloc( r.size() );
should be:
char **p = (char**)malloc( r.size() * sizeof(char *) );
which shows how often I use malloc these days!
精彩评论