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];
 }

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。