I have a large NSArray (wordDictionary) and I am creating smaller sub-arrays from it inside a for-loop. If the for-loop is set to 20,000 iterations everything works just fine. But if I increase the for-loop iterations to 200,000 iterations I get a malloc error... Why is that?
I noticed that if I move the sub-array assignment from inside the loop to outside the loop, it solves the problem!(?) Note that all sub-arrays are identical in both cases (this is just to demonstrate the issue). Here is the code with the assignment inside the loop (which causes the malloc error):
NSArray *subArray;
//subArray = [wordDictionary subarrayWithRange:(NSRange){50000,20000}];
for (int i=0;i<200000;i++)
{
subArray = [wordDictionary subarrayWithRange:(NSRange){50000,20000}];
testBool = [subArray containsObject:@"hello"];
}
NSLog(@"Done");
The code above works if the sub-array assignment is moved outside the loop (as shown by the commented line)
In the error message I get the following is included:
* mach_vm_map(size=8388608) failed (error code=3) error: can't allocate region Terminating app due to uncaught exception 'NSMallocException' reason: '* NSAllocateObject(): attempt to allocate object of class '__NSArrayI' failed' libc++abi.dylib: terminating with uncaught exception of type NSException
Any hints as to what could be causing this and how to fix it are welcome!! Thanks!!