【问题标题】:nil in gdb is not defined as 0x0?gdb 中的 nil 未定义为 0x0?
【发布时间】:2011-05-07 00:44:25
【问题描述】:

我正在使用 gdb(在 Xcode 内部)逐步执行一些简单的 Objective-C 代码,并注意到一些奇怪的东西。这是相关的sn-p:

NSString *s = nil;
int x = (s == nil);

正如我所料,这两行之后x 的值是1。奇怪的是,如果我在 gdb 中尝试类似的东西,它就不一样了:

(gdb) print ret
$1 = (NSString *) 0x0
(gdb) print (int)(ret==nil)
$2 = 0
(gdb) print nil
$3 = {<text variable, no debug info>} 0x167d18 <nil>

似乎 gdb 对 nil 有一些定义,而不是 Objective-C 使用的 (0x0)。有人可以解释这里发生了什么吗?

【问题讨论】:

    标签: objective-c gdb null


    【解决方案1】:

    在编译代码时,nil 是一个预处理器常量,定义为 __null(一个特殊的 GCC 变量,用作 NULL)、0L0

    <objc/objc.h>
    #ifndef nil
    #define nil __DARWIN_NULL /* id of Nil instance */
    #endif
    
    <sys/_types.h>
    #ifdef __cplusplus
    #ifdef __GNUG__
    #define __DARWIN_NULL __null
    #else /* ! __GNUG__ */
    #ifdef __LP64__
    #define __DARWIN_NULL (0L)
    #else /* !__LP64__ */
    #define __DARWIN_NULL 0
    #endif /* __LP64__ */
    #endif /* __GNUG__ */
    #else /* ! __cplusplus */
    #define __DARWIN_NULL ((void *)0)
    #endif /* __cplusplus */
    

    那么,gdb 在运行时获取的nil 来自哪里?您可以从 gdb 给出的消息中看出 nil 是位于该地址的变量的名称:

    (gdb) p nil
    $1 = {<text variable, no debug info>} 0x20c49ba5da6428 <nil>
    (gdb) i addr nil
    Symbol "nil" is at 0x20c49ba5da6428 in a file compiled without debugging.
    

    不出所料,它的值是0

    (gdb) p *(long *)nil
    $2 = 0
    (gdb) x/xg nil
    0x20c49ba5da6428 <nil>: 0x0000000000000000
    

    这个变量从何而来? GDB 可以告诉我们:

    (gdb) i shared nil
      3 Foundation        F -                 init Y Y /System/Library/Frameworks/Foundation.framework/Versions/C/Foundation at 0x20c49ba5bb2000 (offset 0x20c49ba5bb2000)
    

    确实,当我们检查Foundation中定义的符号时,我们发现nil

    $ nm -m /System/Library/Frameworks/Foundation.framework/Foundation | grep nil$
    00000000001f4428 (__TEXT,__const) external _nil
    

    【讨论】:

      【解决方案2】:

      它指向内存中的地址,而不是变量内容。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-05
        • 1970-01-01
        • 2019-12-19
        • 2020-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-13
        相关资源
        最近更新 更多