title: Memory issue in releasing memory in Callback from Objective C to C# in Unity application
body: <p>I need to pass char* from Objective C to C# in Unity application.
  The issue now is when char* is released using free(), the application crash.</p>
  
  <p>I have a callback function in Objective C side as </p>
  
  <pre><code>Unitybridge.mm
  
  static UnityMultipleDevicesCallback MultipleDevicesLastCallBack = NULL;
  void MultipleDevicesConnectCallback(UnityMultipleDevicesCallback callbackMethod)
  {
      NSLog(@"callback is assigned");
      MultipleDevicesLastCallBack = callbackMethod;//a simple assignment using the connect method
  
  }
  
  void MultipleDevicesCallMethod(NSMutableArray *devices)
  {
      NSLog(@"devices: %@", devices);
      if(MultipleDevicesLastCallBack != NULL){
          @autoreleasepool {
             devs_ = (char*)malloc([devices count]+1 * sizeof(char));
  
             for (NSString *s in devices) {
  
                 if(strlen(devs_) &gt; 0){
                     const char *d = "/";
                     strcat(devs_,d);
                     strcat(devs_, [s UTF8String] );
                 }
                 else{
                     strcpy(devs_, [s UTF8String]);
                 }
  
             }           
          }
  
          MultipleDevicesLastCallBack(devs_);
  
      }
  }
  void Freedevs_()
  {
  
      if(devs_!=nullptr){
          free(devs_);
          NSLog(@"devs_ is free now");
      }
  
  }
  </code></pre>
  
  <p>At C# side,</p>
  
  <pre><code>     //
      [DllImport ("__Internal")]
      private static extern void Freedevs_();
      //Callback
      public delegate void UnityMultipleDevicesCallbackDelegate(string devices);
      [DllImport ("__Internal")]
      public static extern void MultipleDevicesConnectCallback(UnityMultipleDevicesCallbackDelegate callbackMethod);
      [MonoPInvokeCallback(typeof(UnityMultipleDevicesCallbackDelegate))]
      private static void MultipleDevicesCallback(string devices)
      {
  
          BLEdevices = (String)devices.Clone();
          Debug.Log ("Multiple devices callback now " + BLEdevices);
          //Freedevs_ ();
      }
  </code></pre>
  
  <p>I tried two options. One is <code>@autoreleasepool</code> and second one is without using <code>@autoreleasepool</code>, I call <code>void Freedevs_()</code>.</p>
  
  <p>Using <code>@autoreleasepool</code>, not sure sometimes it works and sometimes the application crash. If I call Freedevs_ (), definitely the application crash. </p>
  
  <p>What could be the solution for this?</p>