I'm following through one of the very early examples in Learning Objective-C on the Mac. My code is almost exactly the same as the code in the book (a couple spaces and trivial parentheses may differ). It looks like this:
#import <Foundation/Foundation.h>
BOOL areIntsDifferent (int thing1, int thing2) {
if (thing1 == thing2) {
return NO;
}
else {
return YES;
}
}
NSString * boolString (BOOL yesNo) {
if (yesNo == NO) {
return (@"NO");
}
else {
return (@"YES");
}
}
int main (int argc, const char * argv[]) {
BOOL areTheyDifferent;
areTheyDifferent = areIntsDifferent(5, 5);
NSLog(@"are %d and %d different? %@", 5, 5, boolString(areTheyDifferent));
areTheyDifferent = areIntsDifferent(23, 42);
NSLog(@"are %d and $d different? %@", 23, 42, boolString(areTheyDifferent));
return 0;
}
When I run the code, this is what I get in the console:
[Session started at 2009-12-19 01:41:37 -0500.]
GNU gdb 6.3.50-20050815 (Apple version gdb-1346) (Fri Sep 18 20:40:51 UTC 2009)
Copyright 2004 Free Software Foundation, Inc.
GDB i开发者_StackOverflow中文版s free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "x86_64-apple-darwin".tty /dev/ttys001
Loading program into debugger…
Program loaded.
run
[Switching to process 3125]
Running…
2009-12-19 01:41:38.432 BOOL Party[3125:a0f] are 5 and 5 different? NO
Program received signal: “EXC_BAD_ACCESS”.
sharedlibrary apply-load-rules all
I'm not sure why this is happening. I do know that it has something to do with the boolString
function, because when I comment out the call to it, the program runs fine. My gut tells me that this has something to do with some new memory management stuff in Snow Leopard (this book predates Snow Leopard by about six months). Anyone know what the problem might be?
You have a typo in line 30. You want %d, not $d. Because you're missing the second decimal placeholder, you end up passing 42 to the %@, and NSLog tries to dereference memory location 42 as if it's the pointer to a string, and you crash.
精彩评论