Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

malloc + Automatic Reference Counting?

If I use malloc along with Automatic Reference Counting, do I still have to manually free the memory?

int a[100];
int *b = malloc(sizeof(int) * 100);
free(b);
like image 262
Stas Jaro Avatar asked May 07 '12 02:05

Stas Jaro


People also ask

Why is automatic reference counting a type of garbage collection mechanism?

Automatic Reference counting or ARC, is a form of garbage collection in which objects are deallocated once there are no more references to them, i.e. no other variable refers to the object in particular.

What is automatic reference counting in Swift explain how it works?

Structures and Classes in Swift (Heap, Stack, ARC) Automatic Reference Counting (ARC) is to track and manage the app's memory usage . ARC automatically frees up the memory used by class instances when those instances are no longer needed.

How do you resolve a strong reference cycle in closures?

You resolve a strong reference cycle between a closure and a class instance by defining a capture list as part of the closure's definition. A capture list defines the rules to use when capturing one or more reference types within the closure's body.

How do I find reference count in Objective C?

You can do this by putting break points or using print(CFGetRetainCount(CFTypeRef!)) function in your code . You can also increment the reference count of an Object using the CFRetain function, and decrement the reference count using the CFRelease function. CFRetain(CFTypeRef cf);CFRelease(CFTypeRef cf);


3 Answers

Yes, you have to code the call to free yourself. However, your pointer may participate in the reference counting system indirectly if you put it in an instance of a reference-counted object:

@interface MyObj : NSObject {
    int *buf;
}
@end

@implementation MyObj

-(id)init {
    self = [super init];
    if (self) {
        buf = malloc(100*sizeof(int));
    }
}
-(void)dealloc {
    free(buf);
}

@end

There is no way around writing that call to free - one way or the other, you have to have it in your code.

like image 89
Sergey Kalinichenko Avatar answered Sep 28 '22 07:09

Sergey Kalinichenko


Yes. ARC only applies to Objective-C instances, and does not apply to malloc() and free().

like image 27
Greg Hewgill Avatar answered Sep 28 '22 06:09

Greg Hewgill


Some 'NoCopy' variants of NSData can be paired with a call to malloc which will free you from having to free anything.

NSMutableData can be used as somewhat higher-overhead version of calloc which provides the convenience and safety of ARC.

like image 35
Integer Poet Avatar answered Sep 28 '22 07:09

Integer Poet