Q:

Memory Leak using C style Function in Objective C

If I declare a function such as:
NSString* createAString(std::string toConvert);

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

I was under the impression that because I didn't call alloc on the string it will be in the autorelease scope.
When I run this code XCodes memory leak detector is telling me there is a memory leak from this point. Can I not mix C style functions and Objective C types in this way or is there more of a fundamental problem at hand?
Cheers
Stubear

A:

There's nothing wrong with your code. You can mix C-style functions in Objective-C codes. I don't see any problem with the retain/release of Obj-C objects, nor new/delete of C++ objects.
But the name of your function violates the Create Rule. i.e. if the name of a function or a method contains alloc, create or copy, it is assumed to return an NSObject or a CF object with retain count 1. The XCode static analyzer works assuming this rule. You also work with this rule in mind. Otherwise the retain/release would be messed up.
Try Build&analyze this file.
#import <CoreFoundation/CoreFoundation.h>

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

You can see the result of the analyzer changes if you (un)comment CFRelease.  You don't have to provide the definition of FooCreate. Even if you do provide, the current analyzer doesn't look into it, instead it relies on the function name.
Your code returns an autoreleased variable even though the method name has create in it. That might have confused the analyzer to give a false positive.

