C语言 在 GDB 中遇到某个断点时如何执行特定操作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6517423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to do an specific action when a certain breakpoint is hit in GDB?
提问by Thangaraj
I am looking for a way to do some action when a particular break point hits in gdb.
我正在寻找一种在 gdb 中遇到特定断点时执行某些操作的方法。
Basically I have some memleak in my program. When malloc and free function hits, I need to enter into the function (step) and collect some basic information like the addr and size (basically print there values). Once done resume my program.
基本上我的程序中有一些内存泄漏。当 malloc 和 free 函数命中时,我需要进入函数(步骤)并收集一些基本信息,如 addr 和 size (基本上打印那里的值)。完成后恢复我的程序。
Do we have any good way to do this?
我们有什么好的方法可以做到这一点吗?
回答by Fredrik Pihl
For example, here is how you could use breakpoint commands to print the value of x at entry to foo whenever x is positive.
例如,这里是如何使用断点命令在 x 为正数时将 x 的值打印到 foo 的方法。
break foo if x>0
commands
silent
printf "x is %d\n",x
cont
end
If the first command you specify in a command list is silent, the usual message about stopping at a breakpoint is not printed. This may be desirable for breakpoints that are to print a specific message and then continue. If none of the remaining commands print anything, you see no sign that the breakpoint was reached. silent is meaningful only at the beginning of a breakpoint command list.
如果您在命令列表中指定的第一个命令是silent,则不会打印有关在断点处停止的常见消息。对于要打印特定消息然后继续的断点,这可能是可取的。如果其余命令都没有打印任何内容,您就看不到到达断点的迹象。无声仅在断点命令列表的开头有意义。
One application for breakpoint commands is to compensate for one bug so you can test for another. Put a breakpoint just after the erroneous line of code, give it a condition to detect the case in which something erroneous has been done, and give it commands to assign correct values to any variables that need them. End with the continue command so that your program does not stop, and start with the silent command so that no output is produced. Here is an example:
断点命令的一种应用是补偿一个错误,以便您可以测试另一个错误。在错误的代码行之后放置一个断点,给它一个条件来检测错误的情况,并给它命令为任何需要它们的变量分配正确的值。以 continue 命令结束,这样您的程序就不会停止,并以silent命令开始,以便不产生任何输出。下面是一个例子:
break 403
commands
silent
set x = y + 4
cont
end
回答by Ben
To clarify Fredrik's answer, commands(or just command, it seems) automatically knows you just set a breakpoint. That is, what Fredrik is showing isn't a multi-line breakcommand, it's two separate commands: break, and commands. It looks like this:
为了澄清 Fredrik 的答案,commands(或只是command,似乎)自动知道您只是设置了一个断点。也就是说,Fredrik 显示的不是多行break命令,而是两个单独的命令:break, 和commands。它看起来像这样:
(gdb) break 989
Breakpoint 23 at 0x7fffe2761dac: file foo.cpp, line 989.
(gdb) command
Type commands for breakpoint(s) 23, one per line.
End with a line saying just "end".
>silent
>print result
>end
(gdb) c
Continuing.
= {elems = {0, 0}}
(gdb)

