views:

820

answers:

2

In C, something like the following would be a disaster (ie, a memory leak) because you're returning a pointer to memory that you will never be able to free:

NSString* foo()
{
  return [NSString stringWithFormat:@"%i+%i=%i", 2, 2, 2+2];
}

Is that in fact totally fine in Objective-C since the memory that the returned pointer points to will be autoreleased? Even if it is OK, is it frowned upon for any reason? Any reason to prefer the C style, as below?

void foo(NSString ** modifyMe)
{
  *modifyMe = [NSString stringWithFormat:@"%i+%i=%i", 2, 2, 2+2];
}
+4  A: 

Functions in Cocoa obey the same memory management rules as everything else in Cocoa. Your first example is perfectly fine.

Chris Hanson
Thanks Chris! Upon reflection this really should've been obvious. But I guess only obvious once you finally have your head around memory management in Objective-C. So perhaps this will have value for people. Still, I'll probably be more and more tempted to delete the question out of embarrassment!
dreeves
+2  A: 

Not only is it OK in Objective-C, but it’s not inherently a problem in C, as long as you have well-defined ownership semantics.

CFStringRef foo()
{
    return CFStringCreateWithFormat(NULL, CFSTR("%i+%i=%"), 2, 2, 2+2);
}

void bar()
{
    CFStringRef str = foo();
    CFRelease(str);
    // Nothing leaked.
}
Ahruman
This wouldn't be correct use of Core Foundation though, as the name of "foo" doesn't contain the word "Create" or "Copy" to indicate it hands back an object the caller must release...
Chris Hanson
Very true, although I think few people would suggest “foo” is a good function name in any real-world context… well, except those idiots who designed the C standard library. ;-)
Ahruman
Can't stress the need for "Create" or "Copy". I would die if I had to maintain code like this.
bentford