How to view a pointer like an array in GDB?

Suppose defined: int a[100] Type print a then gdb will automatically display it as an array:1, 2, 3, 4.... However, if a is passed to a function as a parameter, then gdb will treat it as a normal int pointer, type print a will display:(int *)0x7fffffffdaa0. What should I do if I want to view a as an array?


See here. In short you should do:

p *array@len

*(T (*)[N])p where T is the type, N is the number of elements and p is the pointer.


Use the x command.

(gdb) x/100w a

As @Ivaylo Strandjev says here, the general syntax is:

print *my_array@len
# OR the shorter version:
p *my_array@len

Example to print the first 10 bytes from my_array:

print *my_array@10

However, if that looks like garbage since it tries to interpret the values as chars, you can force different formatting options like this:

  1. print/x *my_array@10 = hex
  2. print/d *my_array@10 = signed integer
  3. print/u *my_array@10 = unsigned integer
  4. print/<format> *my_array@10 = print according to the general printf()-style format string, <format>

Here are some real examples from my debugger to print 16 bytes from a uint8_t array named byteArray. Notice how ugly the first one is, with just p *byteArray@16:

(gdb) p *byteArray@16
$4 = "\000\001\002\003\004\005\006\a\370\371\372\373\374\375\376\377"
(gdb) print/x *byteArray@16
$5 = {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff}
(gdb) print/d *byteArray@16
$6 = {0, 1, 2, 3, 4, 5, 6, 7, -8, -7, -6, -5, -4, -3, -2, -1}
(gdb) print/u *byteArray@16
$7 = {0, 1, 2, 3, 4, 5, 6, 7, 248, 249, 250, 251, 252, 253, 254, 255}

In my case, the best version is the last one where I print the array as unsigned integers, since it is a uint8_t array after-all:

(gdb) print/u *byteArray@16
$7 = {0, 1, 2, 3, 4, 5, 6, 7, 248, 249, 250, 251, 252, 253, 254, 255}