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];
}
2
  • BTW, your second example will fail. You cannot re-assign a pointer inside of a function because the pointer itself is copy-by-value. If you want your second example to work, you must use NSString **modifyMe as the parameter... Commented Jan 11, 2009 at 13:42
  • I generally refer to the pattern in the second example as an "out-parameter". Don't know if anyone else does, but that's what I call it. Commented Feb 9, 2013 at 12:41

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

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!
2

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.
}

3 Comments

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...
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. ;-)
Can't stress the need for "Create" or "Copy". I would die if I had to maintain code like this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.