0

I am trying to debug this line of code. It is not my code but have to find what is wrong. self.events is an NSMutableArray.

- (nullable NSArray<id> *)getEvents:(NSUInteger)numberOfEvents {
    
    if (self.events.count == 0) {
        return nil;
    }
    
    NSLog(@"min = %ld", MIN(numberOfEvents, self.events.count));
    
    return [self.events subarrayWithRange:NSMakeRange(0, MIN(numberOfEvents, self.events.count))];
    
}

- (NSUInteger)numberOfEvents {
    return self.events.count;
}

Error occurs in this line

   return [self.events subarrayWithRange:NSMakeRange(0, MIN(numberOfEvents, self.events.count))];

I Get the following exception. I can not reproduce the error. On my side it works ok.

EXC_BAD_ACCESS: count > getObjects:range: > Attempted to dereference garbage pointer 0x9f1ffdcac950.

Any help or ideas appreciated!

stefanosn
  • 3,264
  • 10
  • 53
  • 79

1 Answers1

0

Arrays are indexed from zero. If you have an array that has a count of 4, it's indexes go from 0 to 3.

I think you want:

return [self.events subarrayWithRange:NSMakeRange(0, MIN(numberOfEvents, self.events.count - 1))];
Scott Thompson
  • 22,629
  • 4
  • 32
  • 34
  • I agree but if it was an index out of bounds the stacktrace would give me index out of bounds error am i right? I might be wrong just askingyou because you are more experienced. The EXC_BAD_ACCESS: count > getObjects:range: > Attempted to dereference garbage pointer 0x9f1ffdcac950. error. Doesn’t that error mean that is a memory leak? – stefanosn Oct 23 '21 at 15:34
  • Not in Objective-C. Swift gives you index out of bounds protection, but Objective-C does not. The system has read in what is supposed to be an address (it probably is looking for an object pointer) and what it read from memory is not a valid address so I throws an exception. The memory probably contains whatever is lying around after the memory that is storing your array. – Scott Thompson Oct 23 '21 at 16:09
  • I see at this post that it gives... https://stackoverflow.com/questions/22961013/objective-c-slicing-an-array-gives-index-out-of-bounds-error this is different situation? – stefanosn Oct 23 '21 at 18:15