Memory leak using C style Function in Objective C

If I declare a function, for example:

NSString* createAString(std::string toConvert);

NSString* createAString(std::string toConvert)
{
      return [NSString stringWithUTF8String:toConvert.c_str()];
}

I got the impression that due to the fact that I did not call alloc on the line, it would be in the autorelease area.

When I run this code, the XCodes memory leak detector tells me that there is a memory leak from this point. Can I not mix C-style functions and Objective-C types this way, or is there another fundamental problem?

Cheers Stubear

+3
source share
5 answers

. C- Objective-C. / Obj-C, / ++.

Create Rule. .. alloc, create copy, , NSObject CF 1. XCode , , . . / .

.

#import <CoreFoundation/CoreFoundation.h>

extern CFStringRef FooCreate(void);
int main (int argc, const char * argv[]) {
    CFStringRef string=FooCreate();
    /* CFRelease(string); */
    return 0;
}

, (un) CFRelease. FooCreate. , , .

, create. , , .

+2

@ Yuji .

, , C, " Cocoa" :

//NSString+STDConversion.h
@interface NSString (STDConversion)

+ (NSString *) stringWithStdString:(std::string toConvert);

@end

//NSString+STDConversion.mm (note the .mm extension)
@implementation NSString (STDConversion)

+ (NSString *) stringWithStdString:(std::string toConvert) {
  return [NSString stringWithUTF8String:toConvert.c_str()];
}

@end

:

std::string myString = "This is my string";
NSString * myCocoaString = [NSString stringWithStdString:myString];
+2

, (++), ? ?

, , , LLVM, , , ++ ( , ). - , .

0

.

, , , . XCode , /, , .

Also, as already mentioned, your use of "create" violates the Objective-C naming convention. You should rename this to stringFromStdString or something similar. For bonus points you can make this an extension of the NSString class.

0
source

Check if this is being called from outside the pool (stringWithUTF8String: uses it). Try to wrap this in

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    //...
[pool drain];

If it solves the problem, then you (as you said) are outside the scope of the region.

0
source

Source: https://habr.com/ru/post/1751746/


All Articles