How to view a pointer like an array in GDB?

CGdb

C Problem Overview


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?

C Solutions


Solution 1 - C

See here. In short you should do:

p *array@len

Solution 2 - C

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

Solution 3 - C

Use the x command.

(gdb) x/100w a

Solution 4 - C

How to view or print any number of bytes from any array in any printf-style format using the gdb debugger

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

[Recommended!] Custom printf-style print formatting: however, if the commands above look 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, with the correct representation I want to see, is the last one where I print the array as unsigned integers using print/u, since it is a uint8_t unsigned integer 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}

Solution 5 - C

(int[100])*pointer worked for me thanks to suggestion in the comments by @Ruslan

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCDTView Question on Stackoverflow
Solution 1 - CIvaylo StrandjevView Answer on Stackoverflow
Solution 2 - CR.. GitHub STOP HELPING ICEView Answer on Stackoverflow
Solution 3 - CascheplerView Answer on Stackoverflow
Solution 4 - CGabriel StaplesView Answer on Stackoverflow
Solution 5 - CAli80View Answer on Stackoverflow