2016-03-04 25 views
1

我寫它使用getopt功能的簡單程序:爲什麼gdb得到錯誤的「optind」變量值?

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 

int main(int argc, char **argv) 
{ 

     char *fname; 
     int c; 

     printf("Before getopt: optind is %d, address is %p \n", optind, &optind); 

     while ((c = getopt(argc, argv, "f:")) != -1) 
       switch (c) { 
       case 'f': 
         fname = optarg; 
         break; 
       } 

     printf("After getopt: optind is %d, address is %p \n", optind, &optind); 
     return 0; 
} 

執行它,輸出:

# ./test -f 1 
Before getopt: optind is 1, address is 0x601040 
After getopt: optind is 3, address is 0x601040 

但使用gdb當調試它,一些奇怪的事情發生了:

13    printf("Before getopt: optind is %d, address is %p \n", optind, &optind); 
(gdb) n 
Before getopt: optind is 1, address is 0x601040 
15    while ((c = getopt(argc, argv, "f:")) != -1) 
(gdb) p &optind 
$1 = (int *) 0x7ffff7dd42a0 <optind> 
(gdb) n 
16      switch (c) { 
(gdb) n 
18        fname = optarg; 
(gdb) 
19        break; 
(gdb) p &optind 
$2 = (int *) 0x7ffff7dd42a0 <optind> 
(gdb) p optind 
$3 = 1 

我可以看到使用p optind命令,它輸出1(應該是3),而這個變量地址是0x7ffff7dd42a0,而不是0x601040

使用readelf命令:

# readelf -a test | grep optind 
000000601040 000600000005 R_X86_64_COPY  0000000000601040 optind + 0 
6: 0000000000601040  4 OBJECT GLOBAL DEFAULT 25 [email protected]_2.2.5 (2) 
54: 0000000000601040  4 OBJECT GLOBAL DEFAULT 25 [email protected]@GLIBC_2.2.5 

它還顯示一個optind,和其地址應該是0x601040。所以當使用gdb時,爲什麼從0x7ffff7dd42a0得到optind?它是什麼?

更新
使用最新的gdb 7.11,並找到這個問題已得到修復。

回答

1

這是一個obscure gdb bug,由另一個不知名的功能稱爲複製重定位。

+1

剛使用最新的'gdb 7.11',發現這個問題已經修復。 –

相關問題