程序退出时出现JNA错误

时间:2011-04-26 12:42:09

标签: java c++ jna

所以我在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;
}

和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 instruction at "%08X" referenced memory at "%08x". The memory could not be "read".

尝试手动free() char**或每个人char*

时出现同样的错误

有人可以告诉我我做错了什么吗?或者至少指出我们还有更多的资源?

1 个答案:

答案 0 :(得分:1)

此:

 *p = (char*)malloc( it->size() );

应该是:

 *p = (char*)malloc( it->size() + 1);

我刚注意到:

 char **p = (char**)malloc( r.size() );

应该是:

 char **p = (char**)malloc( r.size() * sizeof(char *) );

显示我最近经常使用malloc!