views:

146

answers:

4

I'm somewhat new to objective-c and I'm not sure what the correct memory management for this code is.

const unsigned char * data =(const unsigned char *) [string UTF8String];

When I call free on data I get an error. Do I need to clean up after this call?

thanks!

+5  A: 

No. "UTF8String" does not contain the words alloc, copy, retain, or create. Thus, you're not responsible for that memory.

Note that if you want that data to stick around after string is released, you should copy it; by the contract, you're not responsible for that memory, but you are also not guaranteed that it will last beyond the scope of the object that gave it to you.

BJ Homer
That C string gets freed when the NSString is deallocated. (Or the internal state of the object changes.)
Georg
This is dangerous advice. A lot of methods that deal with C pointers do require you to free the memory. The alloc copy retain rule is for objects.
Chuck
@Chuck: I've added a note about "create", which would take care of the Core Foundation objects as well. Can you give an example of a method that would require the caller to free the memory that is not covered by that rule?
BJ Homer
It is safe to release the string object because data is a pointer to a new memory location storing the characters returned by UTF8String. The data variable is not an id type. It will not respond to objective-c messages.
falconcreek
It's also helpful to know that even for ObjC objects, there are exceptions to the memory management rules. These will be noted in the documentation. Eg. see NSPropertyListSerialization's -dataFromPropertyList:format:errorDescription:
Hwee-Boon Yar
+2  A: 

You do not need to free it.

In Cocoa, if a method does not contain the words alloc, init, or copy, you do not own the object that is returned from said method.

-UTF8String actually points to the cstring representation of the NSString object you are calling it on. When the object's state changes, the UTF8String also changes.

Jacob Relkin
There is no object returned from this method so the memory management rules for objects are irrelevant.
Chuck
I always thought what happens is the string is converted to an NSData object with `-dataUsingEncoding:NSUTF8StringEncoding` and then the the result is the `bytes` method from that `NSData` object. I've never bothered to try and look under the hood so I'm likely wrong about this.
dreamlax
+3  A: 

As stated in the documentation, it is automatically freed the same way an autoreleased object would be.

Chuck
A: 

technically speaking, free() is used to remove memory allocated using malloc() from the heap. malloc() was not used to allocate the memory. remember that objective-c is c with extensions. the data variable will remain in memory based on the c language 'scoping' rules.

falconcreek