andyvn22
andyvn22

Reputation: 14824

Running code returns garbage; typing in debugger returns correct result

Here's the code after which I set a breakpoint (I added the casts to exactly match what I typed in GDB, but it had the same result without them):

NSUInteger addedRefOrder = (NSUInteger)[(NSArray*)[sourceMap tileRefsAtX:[addedRef x] y:[addedRef y]] indexOfObject:addedRef];

Here's what I typed in the GDB:

(gdb) print (NSUInteger)[(NSArray*)[sourceMap tileRefsAtX:[addedRef x] y:[addedRef y]] indexOfObject:addedRef]
$2 = 1
(gdb) print addedRefOrder
$3 = 9223372036854775807

For the record, I'm fairly sure that latter value is NSNotFound. What on earth does this problem imply is going on? How do I even begin to debug this?

EDIT: I am positive the object is in the array. NSNotFound IS returned, but it is NOT correct. Here's another situation elsewhere in the same app:

NSPoint irisPoint = NSMakePoint([currentObject x], [currentObject y]);

Breakpoint right after that line:

(gdb) print irisPoint
$1 = {
  x = 4301764096, 
  y = 4301764096
}
(gdb) print [currentObject x]
$2 = 4
(gdb) print NSMakePoint([currentObject x], [currentObject y])
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000018
0x00007fff885e010a in objc_msgSend ()

Upvotes: 1

Views: 301

Answers (2)

andyvn22
andyvn22

Reputation: 14824

It turns out the problem was that x and y were of type NSInteger, and the compiler was having trouble keeping them straight from some other CGFloat x and y methods.

The solution in the end was to explicitly cast currentObject to the correct type.

Upvotes: 0

robottobor
robottobor

Reputation: 11772

It seems you're not doing the following check, which you need to before using addedRefOrder.

if (addedRefOrder == NSNotFound) {
   NSLog(@"Object %@ not found in array %@", addedRef, array);
}

If it is NSNotFound, then it's not garbage value and I wouldn't question this result and break out the debugger before looking elsewhere in the code. What makes you think it's not right? Usually these things are our own fault. You may have overlooked some problem with your logic outside the scope of this code snippet.

If the above is true, do a review of your code to figure out why it would not be in the array.

One thing to check would be your implemention of isEqual: for the addedRef object's class. Because that is how the array determines that the object is in the array or not.

Also I wouldn't trust the result of the first line in the debugger. You have just called all those methods a second time and there could be anything that could be going on in those calls that would affect the return value. Maybe the second time you call it, it actually IS in the array due to some side effect.

It could also be some concurrency issue, which you should be able to rule out easily if you're not using threads. If you are then I'd look at the usual suspects there.

Upvotes: 2

Related Questions