Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the memory of returned C types handled under GC?

According to the documentation for NSString's method -UTF8String:

The returned C string is automatically freed just as a returned object would be released; you should copy the C string if it needs to store it outside of the autorelease context in which the C string is created.

So under retain/release memory management, the following method:

- (const char*) giveMeACString
{
    NSString* string = @"I'm a string!";
    return [string UTF8String];
}

is fine, so long as the calling method treats the returned const char* as it would an autoreleased object.

However, under garbage collection there isn't an autorelease context, as far as I'm aware. And C types aren't garbage collected, so it doesn't look like the GC will treat the returned pointer as it would a returned object.

What is its lifespan tied to? Is it still freed at a point in the thread's runloop that is reliably `later on', or does it behave differently under GC than under non-GC?

like image 982
Chris Devereux Avatar asked Jun 05 '11 16:06

Chris Devereux


1 Answers

I think the memory is allocated from garbage collected memory and the return type is __strong const char*. This means that it will be collected in the normal way when it is not reachable from the root set of pointers.

That basically means you need to store it in a pointer variable that is marked as __strong or it will be collected at some point.

I'd speculate that an immutable string maintains a reference to the UTF8 version of itself, so it only has to calculate it once and therefore the UTF8 string probably won't go away until the NSString does which is why you don't have to worry about it disappearing normally.

like image 106
JeremyP Avatar answered Oct 02 '22 18:10

JeremyP