arkaeologic
arkaeologic

Reputation: 85

array index blows up obj c

I am writing an iPhone app in Xcode 4.6.3.

I don't really know how to ask this question, but during operation, an array index goes from 0, which is hardcoded in a method, to 58911 for some reason. The chain is:

- (void)syncInitialState
{
    [self syncState:0]; //value starts hardcoded here
}

then:

- (void)syncState:(int)index
{
    self.state = [macrostate getState:index];
    [self syncState];
}

in Macrostate:

- (NPState *)getState:(int)index
{
    int *singleArray = {&index};
    NSPointerArray *pointerArray = [self subsetFromIntArray:singleArray];
    return (__bridge NPState *)[pointerArray pointerAtIndex:0]; //only one object
}

finally:

- (NSPointerArray *)subsetFromIntArray:(int *)intArray
{
    NSPointerArray *subset = [NSPointerArray strongObjectsPointerArray];
    for (int i=0; i<sizeof(intArray); i++) {
        [subset addPointer:[pointerArrayOfStates pointerAtIndex:intArray[i]]]; //fails
    }
    return subset;
}

Obviously it fails because 58911 is outside the bounds of the pointer array. I have never seen this before. Thanks for reading.

It might help to know that the error is: * Terminating app due to uncaught exception 'NSRangeException', reason: ' -[NSConcretePointerArray pointerAtIndex:]: attempt to access pointer at index 58911 beyond bounds 4' ** First throw call stack: (0x1caa012 0x10e7e7e 0x1ca9deb 0xb1c1ab 0xd8ae 0xd7a5 0x47c6 0x485e 0x567f 0x5d95 0x2d3f 0x10d1c7 0x10d232 0x5c3d5 0x5c76f 0x5c905 0x65917 0x29c5 0x29157 0x29747 0x2a94b 0x3bcb5 0x3cbeb 0x2e698 0x1c05df9 0x1c05ad0 0x1c1fbf5 0x1c1f962 0x1c50bb6 0x1c4ff44 0x1c4fe1b 0x2a17a 0x2bffc 0x26fd 0x2625) libc++abi.dylib: terminate called throwing an exception

Upvotes: 0

Views: 286

Answers (1)

rmaddy
rmaddy

Reputation: 318944

You can't use sizeof to get the length of the int array. You need to add a "length" parameter to your subsetFromIntArray: method and use that instead of sizeof.

Upvotes: 3

Related Questions