public
Last active

NSFastEnumeration over a C array crashing with BAD_ACCESS

  • Download Gist
Array.m
Objective-C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
#import <Foundation/Foundation.h>
 
@interface Array : NSObject <NSFastEnumeration> {
id __strong *_objs;
NSUInteger _count;
}
@end
 
@implementation Array
 
-(id)init {
self = [super init];
if (self){
_objs = (id __strong *)calloc(16,sizeof(*_objs));
}
return self;
}
 
-(void) addObject:(id)object {
_objs[_count] = object;
_count++;
}
 
-(id) objectAtIndex:(NSUInteger)index {
return _objs[index];
}
 
- (NSUInteger) countByEnumeratingWithState: (NSFastEnumerationState*)state
objects: (id __unsafe_unretained*)stackbuf
count: (NSUInteger)len
{
NSUInteger size = _count;
NSInteger count;
state->mutationsPtr = (unsigned long *)size;
count = MIN(len, size - state->state);
if (count > 0)
{
IMP imp = [self methodForSelector: @selector(objectAtIndex:)];
int p = state->state;
int i;
for (i = 0; i < count; i++, p++) {
stackbuf[i] = (*imp)(self, @selector(objectAtIndex:), p);
}
state->state += count;
}
else
{
count = 0;
}
state->itemsPtr = stackbuf;
return count;
}
 
@end
 
 
int main(int argc, char *argv[]) {
@autoreleasepool {
Array *array = [Array new];
[array addObject:@1];
for (id object in array){ // BAD_ACCESS !
NSLog(@"%@",object);
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.