iOS cStringUsingEncoding内存管理问题

Hey, I am trying to convert NSString to a C string using cStringUsingEncoding but I have a memory leak. My understanding is that cStringUsingEncoding returns a pointer to a character array that is only guaranteed to exist for the duration of the NSString object. As such you should copy its contents to another string. Here's where my problem lies...

I have a function that accepts an NSString and turns it into a C-string copy. Just for testing I ran 1,000 iterations of the following method (to ensure no leaks).

 -(void)test{
      NSString *test = [[NSString alloc] initWithString:@"Hello world!"];

      for(int i=0; i<1000; i++)
      {
           char *tmp = [self returnCopiedCString:test];

           //free memory
           free(tmp);
      }

      [test release];
 }
原文地址:https://www.cnblogs.com/huangzizhu/p/4521537.html