I am trying to create a method to quickly and easily create an NSArray from a va_list, however, when I run the method, I receive an exc_bad_access due to some bad memory management somewhere, although I cannot determine where this place is.
Please could you take a look at the code and tell me where and why this is occurring.
Thanks in advanced,
Max.
NSArray *arrayCreate(id firstObject, ...) {
NSMutableArray *objects = [NSMutableArray array];
[objects addObject:firstObject];
va_list args;
va_start(args, firstObject);
id arg;
while ((arg = va_arg(args, id))) {
[objects addObject:arg];
}
va_end(args);
return [objects copy];
}
Usage (just to test that it’s working):
NSLog(@"%@", arrayCreate(@"1", @"2", @"3", @"4"));
You forgot to
nil-terminate your arglist. In C, functions have no way of knowing how many variadic arguments you passed, so it’s common to end a series of pointers with a null pointer (to indicate no more valid input.) Your code appears to be checking for this (arg = va_arg(args, id)will be false when it reachesnil) but your input is missing it.