2

I have this small program:

#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[]) {
   printf("argv[1] -> %s\n", argv[1]); 
}

Which I analyzed in gdb with the following commands:

$ gdb -q  --args foo hello
Reading symbols from foo...
(gdb) break main
Breakpoint 1 at 0x1148: file foo.c, line 5.
(gdb) run
Starting program: /tmp/foo/foo hello

Breakpoint 1, main (argc=2, argv=0x7fffffffea68) at foo.c:5
5          printf("argv[1] -> %s\n", argv[1]);
(gdb) print argv@2
$1 = {0x7fffffffea68, 0x200000000}
(gdb) print *argv@2
$2 = {0x7fffffffecd8 "/tmp/foo/foo", 0x7fffffffece5 "hello"}

I don't understand how argv[1] can yield the string "hello" when the content of argv[1] is 0x200000000 and not 0x7fffffffece5 which is the actual address of the string "hello".

Sisir
  • 4,584
  • 4
  • 26
  • 37
nerdzao
  • 21
  • 2

2 Answers2

0

print argv@2 doesn't do what you think it does. Instead of printing argv[0] and argv[1], it appears to print (&argv)[0] and (&argv)[1].

Here's what I got when I tried debugging your program:

(gdb) p argv
$1 = (char **) 0x7fffffffecd8
(gdb) p argv[0]
$2 = 0x7fffffffeeb8 "/home/a.out"
(gdb) p argv[1]
$3 = 0x0
(gdb) p argv@2
$4 = {0x7fffffffecd8, 0x100000000}
(gdb) p (&argv)[1]
$5 = (char **) 0x100000000
HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
  • Why isn't the second number in `argv@2` located `sizeof(char***)` bytes after the first one then? – bool3max Dec 22 '19 at 10:29
  • @bool3max `argv@2` prints the values of `argv` and of the non-existent pointer located right after `argv` in memory, not their addresses. – HolyBlackCat Dec 22 '19 at 11:03
0

I used the examine command in gdb and now things make sense:

(gdb) x/2xg argv
0x7fffffffea58: 0x00007fffffffecc2      0x00007fffffffecd5
(gdb) x/1s 0x00007fffffffecc2
0x7fffffffecc2: "/tmp/foo/foo"
(gdb) x/1s  0x00007fffffffecd5
0x7fffffffecd5: "hello"
(gdb)
nerdzao
  • 21
  • 2