Malloc + Automatic link counting?

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

int a[100]; int *b = malloc(sizeof(int) * 100); free(b); 
+9
malloc objective-c automatic-ref-counting
source share
4 answers

Yes, you need to program the free call yourself. However, your pointer can participate in the reference counting system indirectly if you put it in an instance of a reference counting 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 to write this call free - anyway, you must have it in your code.

+20
source share

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

+5
source share

In dealloc add a if not nil and assign nil for safe. Do not want to free nil, malloc can be used outside init, etc.

 @interface MyObj : NSObject { int *buf; } @end @implementation MyObj -(id)init { self = [super init]; if (self) { buf = malloc(100*sizeof(int)); } } -(void)dealloc { if(buf != null) { free(buf); buf = null; } } @end 
0
source share

Some "NoCopy" variants of NSData may be associated with calling malloc, which saves you from having to free anything.

NSMutableData can be used as a slightly more complex version of calloc, which provides the convenience and security of ARC.

0
source share

All Articles