views:

145

answers:

3

Hi,

I'm writing a program that calculates the Jacobi algorithm. It's written in Objective-C since it runs on a Mac, but the majority is written in standard C. I'm using a two-dimensional C array and an NSArray containing 5 NSTextField labels.

The following code yields an EXC_BAD_ACCESS error:

for ( int i = 0; i < 5; i++ ) {
     NSString *resultString = [NSString stringWithFormat:@"%g", matrix[i][i] ];
     [[resultLabels objectAtIndex:i] setStringValue:resultString]; // error line
}

Any help?

EDIT

Here's where I init resultLabels:

resultLabels = [[NSArray alloc] initWithObjects:result11, result22, result33, result44, result55, nil];
+1  A: 

If you get the error on that line, then either resultsLabels is released, or the object at i is.

Paul Lynch
`matrix` is a C array, so everything in it is an `int`. Also, I've tried `retaining` `resultLabels` and everything in it and get the same result.
Chris Long
The object at i in your array is a a string, not one of your matrix of ints.
Paul Lynch
Oh sorry; you're right. Working on two projects at once gets a little confusing! ;)
Chris Long
+1  A: 

Most likely, you are referencing an object that has been released. Is your NSArray or objectAtIndex: nil at that point? Can you show the lines where you instantiate these objects?

Don
Sending a message to nil doesn't cause a BAD_ACCESS error.
Paul Lynch
I've tried `retaining` `resultLabels` and everything inside it.
Chris Long
paull - true; I meant memory address 0x0, not nil. Thanks for pointing that out.
Don
Picky detail: nil and address 0x0 are the same, neither will cause a bad access error; messages to nil return nil.
Paul Lynch
I know that you can message nil, but I'm not sure why I never associated 0x0 with nil. Thanks!
Don
I ended up going with a Objective-C based approach, but I'm accepting this answer since he was so helpful in the comments. Thanks for helping! :)
Chris Long
+1  A: 

This isn't the source of your crasher, but the %g format code is for doubles not ints; you want %d.

The items in the array would be automatically retained by the array (objects in Foundation collections are always retained by the collection), so you shouldn't need to send them extra -retain messages. So it would seem as though resultLabels may be getting released somewhere before the crash occurs.

jlehr
Actually, I simplified. It's really a `double` that gets changed later on. The `retainCount` in the `init` method is 1, but it crashes when it gets called in a different method. I thought nothing happens if a message is sent to a `nil` object, which is why this is so puzzling.
Chris Long
Nothing does happen, and your comment elsewhere in this question shows that your NSArray points to 0x4. So I would guess that you have possibly assigned one of your ints to the array pointer somehow.
Paul Lynch