Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

justmyself

macrumors member
Original poster
Jan 2, 2009
32
0
My program quit working so I trimmed it down to the bare bones to try to get to the issue. Strangely this console shows a bus error and my int variable has a value like 188726 in the debugger. Any ideas what's going on here?

int crazy;

crazy = 2;

NSString *cheese[3];
cheese[0] = @"Say cheese 0";
cheese[1] = @"Say cheese 1";
cheese[2] = @"Say cheese 2";
cheese[3] = @"Say cheese 3";

[myText setStringValue:cheese[crazy]];

Strangely, this does work

int crazy;

NSString *cheese[3];
cheese[0] = @"Say cheese 0";
cheese[1] = @"Say cheese 1";
cheese[2] = @"Say cheese 2";
cheese[3] = @"Say cheese 3";

crazy = 2;

[myText setStringValue:cheese[crazy]];
 

lee1210

macrumors 68040
Jan 10, 2005
3,182
3
Dallas, TX
You are overflowing an array, and when you do so other areas of memory change causing unexpected behavior. It sounds like crazy is being corrupted when you assign a value to cheese[3], which is off the end of the array. Once this value is corrupt, it's going to do even worse things when used as a subscript on cheese.

The second one works because after crazy is corrupted you set it's value to what you want.

Make cheese 4 elements and you will be fine. When you declare a C-style array, you use the capacity, not the maximum index.

-Lee
 

justmyself

macrumors member
Original poster
Jan 2, 2009
32
0
Thanks. I can't believe I didn't see that. 4 positions, set the array to 4. Let's pretend this never happened.

Reminds me. If I recall from my C++ classes. C will let you overwrite an array? I remember my instructor telling us the C language assumes your the programmer, it assumes you know what your doing. So if you overwrite an array, it will let you. Of course this is Objective C and xcode.
 

lee1210

macrumors 68040
Jan 10, 2005
3,182
3
Dallas, TX
Objective-C is a superset of C, so any C code means the same thing in Objective-C. C essentially has no net. Arrays are just stored as a pointer to the base of the array. You are given all the power and all the responsibility to manage that. The Cocoa API/framework provides you with nets galore to help save you from making a lot of mistakes. For example, you could have used NSMutableArray, and it would have handled the capacity dynamically for you. The caveat is that you have to store NSObjects. You already are, but you have to wrap primitives like ints before you can store them in an NSMutableArray.

-Lee
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.