8

I have a structure like this :

    struct A 
    {
        int a; 
        char b; 
    };

this structure is referenced at various places in a large code. The pointer to this struct is passed on to different functions and accordingly the variables in this structure are updated. i want to set a watchpoint on variable a in this struct as it travels across many functions. to see how a changes. How do I set this watch point ?

KernelMonk
  • 311
  • 1
  • 5
  • 9

2 Answers2

7

First set a breakpoint where you create an instance of your struct using break, like

break myfile.c:9

Then just use watch to set a watchpoint, like

watch myStructInstance.a

for variable a or

watch *0x7ffff75177f0

for a memory address. The memory address can be obtained easily by using print, like

print &myStructInstance.a

Now every time variable a or the given memory address gets modified gdb will break.

scai
  • 20,297
  • 4
  • 56
  • 72
4

I come with the same problem when debugging my virtual memory simulator. The problem is how to keep a close look at the data inside structs.

I tried using print to check, but that's too noisy. Because I have to print out more than 15 variables.

I also tried using watchpoint, but on my machine, I can only set no more than 4 hardware watchpoints. That's not even close to my goal.

Finally, I find my solution by using user-defined function in .gdbinit file. e.g. if I want to watch array of my structure, using

define lookintoStructs
    if mystruct != 0x0
        print mystruct[0]
        print mystruct[1]
        print mystruct[2]
        print mystruct[3]
        print mystruct[4]
        print mystruct[5]
    end
end

to make it more convenient to use, I'd like to make it hook to my next instruction in gdb.

define hook-next
    lookintoStructs
end

so when I call next or n in gdb, lookintoStructs could be called automatically. works fine for me.