我正在关注Learning Objective-C on the Mac中最早的一个例子。我的代码几乎与书中的代码完全相同(一些空格和平凡的括号可能不同)。它看起来像这样:
#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;
}
当我运行代码时,这就是我在控制台中获得的内容:
[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 is 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
我不确定为什么会这样。我知道它与boolString
函数有关,因为当我注释掉它的调用时,程序运行正常。我的直觉告诉我,这与Snow Leopard中的一些新的内存管理功能有关(这本书比Snow Leopard早了大约六个月)。任何人都知道问题可能是什么?
答案 0 :(得分:8)
第30行有一个拼写错误。你想要%d,而不是$ d。因为你错过了第二个小数占位符,你最终将42传递给%@,并且NSLog尝试取消引用内存位置42,好像它是指向字符串的指针一样,然后崩溃。