GDB: How to force a watchpoint to not be deleted after a function returned?

冷暖自知 提交于 2019-12-05 15:04:19

As GDB: Setting Watchpoints says,

GDB automatically deletes watchpoints that watch local (automatic) variables, or expressions that involve such variables, when they go out of scope, that is, when the execution leaves the block in which these variables were defined.

However, as of release 7.3 (thanks to @Hi-Angel and user parcs on IRC for pointing this out; I missed seeing it right there in the documentation), the watch command accepts a -location argument:

Ordinarily a watchpoint respects the scope of variables in expr (see below). The -location argument tells GDB to instead watch the memory referred to by expr. In this case, GDB will evaluate expr, take the address of the result, and watch the memory at that address. The type of the result is used to determine the size of the watched memory.

On older versions of GDB, you can run this instead, using the example from your question:

eval "watch *(mystruct *)%p", &obj

Note that watching locations on the stack may cause spurious notifications if the memory you're watching gets reused by another function's local variables.

As an alternative, you can automate the setting of a watchpoint on an automatic variable that keeps coming into and out of scope. Set a breakpoint at a point where it's in scope - for example, at the beginning of the function or block in which it's declared - then attach a watch and continue command:

(gdb) break MyFunc
(gdb) commands $bpnum
>watch obj
>continue
>end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!