Changing Int value and bus error

Discussion in 'Mac Programming' started by justmyself, Jan 17, 2009.

  1. macrumors member

    Joined:
    Jan 2, 2009
    #1
    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?

    Strangely, this does work

     
  2. macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #2
    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
     
  3. thread starter macrumors member

    Joined:
    Jan 2, 2009
    #3
    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.
     
  4. macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #4
    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
     

Share This Page