Print the values of variables of a structure array in GDB Print the values of variables of a structure array in GDB arrays arrays

Print the values of variables of a structure array in GDB


You can register python pretty prointer: https://sourceware.org/gdb/onlinedocs/gdb/Writing-a-Pretty_002dPrinter.html and use it to get something like this:

(gdb) p *projections@10$1 = {10, 0, 0, 0, 0, 0, 0, 0, 0, 0 }(gdb)

This is example of a python pretty printer:

>cat my_printer.pyclass projection_printer:    def __init__(self, val):        self.val = val    def to_string(self):        return str(self.val['size'])import gdb.printingdef build_pretty_printer():    pp = gdb.printing.RegexpCollectionPrettyPrinter("")    pp.add_printer('projection', '^projection$', projection_printer)    return ppgdb.printing.register_pretty_printer( gdb.current_objfile(),  build_pretty_printer())

This is a test program:

>cat main.cpp#include <stdlib.h>typedef struct angle{  int a;} angle_t;typedef struct projection {    angle_t angle;    int size;} projection_t;int main(){  projection_t *projections;  projections = (projection_t *)malloc(sizeof(projection_t)*10);  projections[0].size = 10;  projections[0].angle.a = 20;  return 0;}

And this is a gdb session:

>gdb -q -x my_printer.py a.outReading symbols from /home/a.out...done.(gdb) startTemporary breakpoint 1 at 0x4005ac: file main.cpp, line 18.Starting program: /home/a.outTemporary breakpoint 1, main () at main.cpp:1818        projections = (projection_t *)malloc(sizeof(projection_t)*10);(gdb) n19        projections[0].size = 10;(gdb)20        projections[0].angle.a = 20;(gdb)22        return 0;(gdb) p *projections@10$1 = {10, 0, 0, 0, 0, 0, 0, 0, 0, 0 }(gdb)


While not using the @ operand you can try the following to achieve your goal:

(gdb)set $i=0(gdb) set $end=m(gdb) while ($i < $end) >p projections[$i++].size >end

or use

p projections[index].size

to print the size for the given index.


Define a function that prints out each element in a loop. You only need to define the function once. Set $m equal to number of projections you allocated. Then, you can print out everything with one command line input.

(gdb) set $m=4 (gdb) define f>set $i=0>while ($i<$m)> p projections[$i++].size> end>end(gdb) f