GDB不允许我读取argv内存段

时间:2018-08-07 10:55:09

标签: c memory segmentation-fault gdb argv

我有一个用C编写的简单脚本:

#include <stdio.h>

void usage(char *program_name) {
   printf("Usage: %s <message> <# of times to repeat>\n", program_name);
   exit(1);
}

int main(int argc, char *argv[]) {
   int i, count;

//  if(argc < 3)      // If less than 3 arguments are used,
//    usage(argv[0]); // display usage message and exit.

   count = atoi(argv[2]); // convert the 2nd arg into an integer
   printf("Repeating %d times..\n", count);

   for(i=0; i < count; i++)
      printf("%3d - %s\n", i, argv[1]); // print the 1st arg
}

我正在对GDB进行一些测试。

我这样做:

(gdb) run test
Starting program: /home/user/Desktop/booksrc/convert2 test

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7a56e56 in ____strtoll_l_internal () from /usr/lib/libc.so.6

由于程序需要三个argv,因此它会出现分段错误。我评论了进行控制的行。所以它出错了。

(gdb) where
#0  0x00007ffff7a56e56 in ____strtoll_l_internal () from /usr/lib/libc.so.6
#1  0x00007ffff7a53a80 in atoi () from /usr/lib/libc.so.6
#2  0x00005555555546ea in main (argc=2, argv=0x7fffffffe958) at convert2.c:14
(gdb) break main
Breakpoint 1 at 0x5555555546d2: file convert2.c, line 14.
(gdb) run test
The program being debugged has been started already.
Start it from the beginning? (y or n) y
Starting program: /home/user/Desktop/booksrc/convert2 test

Breakpoint 1, main (argc=2, argv=0x7fffffffe958) at convert2.c:14
14     count = atoi(argv[2]); // convert the 2nd arg into an integer
(gdb) cont
Continuing.

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7a56e56 in ____strtoll_l_internal () from /usr/lib/libc.so.6
(gdb) x/3xw 0x7fffffffe958 // this is memory of the "argv" some line before
0x7fffffffe958: 0xffffebfe  0x00007fff  0xffffec22
(gdb) x/s 0xffffebfe
0xffffebfe: <error: Cannot access memory at address 0xffffebfe>
(gdb) x/s 0x00007fff
0x7fff: <error: Cannot access memory at address 0x7fff>
(gdb) x/s 0xffffec22
0xffffec22: <error: Cannot access memory at address 0xffffec22>

理论上,使用“ x / s”,我应该已经在第一个地址中看到了命令行,在第二个地址中看到了“ test”,而在第三个地址中看到了null。但是什么都没有。如果我将该地址复制粘贴到一个ASCII到字符串转换器,它将给我没有任何意义的数据。我在做什么错了?

2 个答案:

答案 0 :(得分:3)

您的平台使用64位指针,因此请尝试:

(gdb) x/3xg 0x7fffffffe958

显示argv数组中的64位指针,然后:

(gdb) x/s 0x00007fffffffebfe

或者只是:

(gdb) p argv[0]

答案 1 :(得分:1)

首先总是检查命令行是否正确

取消注释您的代码中的支票。

然后在gdb中设置参数(在运行之前)

(gdb) set args "hello world" 12