Reputation: 4885
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);
Upvotes: 10
Views: 7561
Reputation: 747
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.
Upvotes: 1
Reputation: 960
In dealloc add an if not nil and assign to nil for safe. Dont want to free nil, malloc might be used outside of 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
Upvotes: 0
Reputation: 727077
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.
Upvotes: 21
Reputation: 994817
Yes. ARC only applies to Objective-C instances, and does not apply to malloc()
and free()
.
Upvotes: 4