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
,並找到這個問題已得到修復。
剛使用最新的'gdb 7.11',發現這個問題已經修復。 –