Skip to content

Instantly share code, notes, and snippets.

@janodev
Created November 1, 2012 19:59
Show Gist options
  • Save janodev/3996072 to your computer and use it in GitHub Desktop.
Save janodev/3996072 to your computer and use it in GitHub Desktop.
NSFastEnumeration over a C array crashing with BAD_ACCESS
#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);
}
}
}
@janodev
Copy link
Author

janodev commented Feb 12, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment