2010-11-09 32 views
4

我正在通過一些簡單的Objective-C代碼與gdb(Xcode內部)並注意到一些奇怪的東西。下面是相關片段:gdb中的nil沒有定義爲0x0?

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具有零比目標-C用途(爲0x0)其他一些定義。有人可以解釋這裏發生了什麼嗎?

回答

9

當正在編譯代碼,nil是定義爲任一__null(一種特殊GCC變量用作NULL0L,或0預處理器常數:

<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 */ 

所以,在什麼地方nil gdb在運行時拾取來自哪裏?您可以從消息告訴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) 

事實上,當我們檢查的基礎定義的符號,我們發現nil

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

大博覽會 – bacar 2012-01-29 01:15:33

1

它指向內存中的地址,而不是變量內容。

相關問題