title: Return String[] from Go using cgo
body: <p>I have to call a Go function from Java. 
  I am using <code>cgo</code> and <code>JNA</code> for doing this.</p>
  
  <p>The only thing that the Go routine does is allocating memory and return a <code>char**</code>. From Java side, I am receiving the <code>char**</code> using <code>String[]</code> as is mentioned in the <a href="https://github.com/java-native-access/jna/blob/master/www/PointersAndArrays.md" rel="nofollow noreferrer">documentation</a>.</p>
  
  <p>Below are the details of the C helper and Go functions:</p>
  
  <pre><code>static char** cmalloc(int size) {
      return (char**) malloc(size * sizeof(char*));
  }
  
  static void setElement(char **a, char *s, int index) {
      a[index] = s;
  }
  
  //export getSearchKeysA
  func getSearchKeysA() **C.char {
      set_char := C.cmalloc(1)
      defer C.free(unsafe.Pointer(set_char))
      C.setElement(set_char, C.CString("hello world"), C.int(0))
      return set_char
  }
  </code></pre>
  
  <p>The Java side: </p>
  
  <pre><code>String[] getSearchKeysA();
  </code></pre>
  
  <p>The error I am getting is: </p>
  
  <pre><code>#
  # A fatal error has been detected by the Java Runtime Environment:
  #
  #  SIGSEGV (0xb) at pc=0x00007fff6b15323e, pid=92979, tid=0x0000000000000c07
  #
  # JRE version: Java(TM) SE Runtime Environment (8.0_192-b12) (build 1.8.0_192-b12)
  # Java VM: Java HotSpot(TM) 64-Bit Server VM (25.192-b12 mixed mode bsd-amd64 compressed oops)
  # Problematic frame:
  # C  [libsystem_kernel.dylib+0x723e]  __pthread_kill+0xa
  #
  # Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
  #
  # An error report file with more information is saved as:
  # /Users/dfb3/datafabric/pocs/go-java-connector/hs_err_pid92979.log
  #
  # If you would like to submit a bug report, please visit:
  #   http://bugreport.java.com/bugreport/crash.jsp
  # The crash happened outside the Java Virtual Machine in native code.
  # See problematic frame for where to report the bug.
  #
  </code></pre>
  
  <p><strong>What I have noticed is that the issue appears when malloc is allocating memory.</strong> </p>
  
  <p>I already tried doing <code>ulimit -c unlimited</code> and removing the <code>defer C.free(unsafe.Pointer(set_char))</code> from the method. </p>
  
  <p>What can be the cause of the error and how can I solve it? Is there any other way of returning a <code>[]string</code> from Go using <code>JNA</code>? </p>
  
  <p>Update because of typo and base on @PeterSO answer  :</p>
  
  <ol>
  <li>I wrote initially malloc(0) but it should be malloc(1) </li>
  <li><code>func C.CString(string) *C.char</code>, it should allocate the memory for me, is
  not?</li>
  </ol>