简体   繁体   English

非常简单的Objective-C程序(Snow Leopard)上的EXC_BAD_ACCESS

[英]EXC_BAD_ACCESS on very simple Objective-C program (Snow Leopard)

I'm following through one of the very early examples in Learning Objective-C on the Mac . 我将继续学习Mac上的Learning Objective-C的早期示例之一。 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 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

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. 我确实知道它与boolString函数有关,因为当我注释掉对它的调用时,程序运行良好。 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). 我的直觉告诉我,这与Snow Leopard中的一些新的内存管理功能有关(这本书比Snow Leopard早了大约六个月)。 Anyone know what the problem might be? 有人知道可能是什么问题吗?

You have a typo in line 30. You want %d, not $d. 您在第30行有一个错字。您需要%d,而不是$ 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. 因为缺少第二个小数位占位符,所以最终将42传递给%@,NSLog尝试取消对内存位置42的引用,就好像它是指向字符串的指针一样,然后崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM