Search code examples
debugginggdbwatchpoint

Setting a watch point in GDB


I am operating a huge code base and want to monitor a value of a particular variable (which is buried deep down inside one of the files)especially when it gets set to zero.

1) Variable does not belong to global scope .Is there a better option than to first set breakpoint into the function where it is defined and then set the watch point?
2) After trying the option in 1 I see that watch point gets deleted after a while saying its out of frame which used this .This way it adds to the tediousness of the procedure since I have to add it again and again?Any workarounds?
3) Is there a way to check ie watch if a particular variable is equal to 0( or any specific constant)?


Solution

  • want to monitor a value of a particular variable

    Often this is not the best approach, especially in large codebases.

    What you really likely want to do is understand the invariants, and assert that they are true on entry and exit to various parts of the code.

    1) Variable does not belong to global scope .Is there a better option than to first set breakpoint into the function where it is defined and then set the watch point?

    No. For automatic (stack) variables you have to be in the scope where the variable is "active".

    What you can do is set a breakpoint on some line, and attach commands to that breakpoint that will set the watchpoint automatically, e.g.

    (gdb) break foo.c:123
    (gdb) commands 1
          silent
          watch some_local
          continue
          end
    

    3) Is there a way to check ie watch if a particular variable is equal to 0

    You can't do that with a watchpoint, but you can with a conditional breakpoint:

    (gdb) break foo.c:234 if some_local == 0