2

Using Valgrind or any other debugger in Linux, how can one see places where a variable is modified. I am using gcc. Note that I don't want to step into the code using gdb. I just want to run the program and have the debugger report me in the end, places where the variable is modified in the code.

MetallicPriest
  • 29,191
  • 52
  • 200
  • 356
  • 3
    possible duplicate of [Can I set a breakpoint on 'memory access' in GDB?](http://stackoverflow.com/questions/58851/can-i-set-a-breakpoint-on-memory-access-in-gdb) – bobbymcr Nov 08 '11 at 07:33

2 Answers2

2

Hm, thinking about it it's not exact duplicate of Can I set a breakpoint on 'memory access' in GDB?, because it asks a little bit more. So:

  1. Use gdb
  2. Find the address you want to watch (hardware watchpoints only work for watching address, so you have to run it to the point where the variable or object are instantiated, take their address and use the watch command on that address.
  3. Attach command to the address to give you a backtrace (or any other info you need to collect) and continue.

So you'll have something like:

p &variable
watch *$$
cmd
bt
c
end

(I am not completely sure with the $$, I normally use the $n as printed by the p command).

Community
  • 1
  • 1
Jan Hudec
  • 73,652
  • 13
  • 125
  • 172
  • If the variable is modified in many places (say, in a tight loop) this will be *unbearably* slow. I would say only use this method if it's your last resort. – tdenniston Nov 08 '11 at 14:31
  • It is not that slow, assuming you want to follow the variable's changes, because the watchpoint above is usually a hardware watchpoint. Software watchpoints (for example, watching t[i]) are considerably slower... – Basile Starynkevitch Nov 09 '11 at 12:10
  • @BasileStarynkevitch: If you add `cmd/bt/c/end`, it *will* be slow. It's the printing of backtraces that slows it down, not the watchpoint. – Jan Hudec Nov 09 '11 at 12:16
  • Agreed. So it depends if the variable changes very often or not. – Basile Starynkevitch Nov 09 '11 at 12:34
1

Use Breakpoint Command Lists to do this in gdb. You will have to know the address of variable to watch. Set watchpoint with a series of commands like this:

 watch *0xfeedface
 commands
 silent
 bt
 cont
 end

You can also optionally save all this output to log file. Look gdb doc for more details.

ks1322
  • 33,961
  • 14
  • 109
  • 164