如何使用 GDB 从多个文件中找到分段错误 [英] How do I find segmentation fault from multiple files using GDB

查看:11
本文介绍了如何使用 GDB 从多个文件中找到分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一次采访中被问到如何使用 GDB 调试 C 程序中的分段错误.

I have been asked in an interview how can you debug segmentation fault in C program using GDB.

我告诉他们我们可以使用 -g 选项编译我们的程序,以便将调试信息添加到二进制文件并可以读取核心转储文件,但是面试官告诉我他是否有 3 到 4 个文件一起编译,但其中一个导致分段错误,那么我们如何在 GDB 中调试?

I told them we can compile our program with -g option so as it add debugging information to binary file and can read core dump file but then interviewer told me if he we have 3 to 4 files compiled together but one of them causing segmentation fault then how do we debug in GDB?

推荐答案

$ gcc -ggdb s1.c s2.c s3.c -o myprog
$ gdb myprog
(gdb) run --arg1 --arg2

GDB 将正常运行程序,当发生分段错误时,GDB 将返回到它的提示符,这与使用核心文件运行 GDB 几乎相同.主要区别在于,当程序在 GDB 内部崩溃时,您可以使用核心文件执行/打印某些操作.(例如,您可以使用 print 来调用程序内部的一些函数.)

GDB will run the program as normal, when the segmentation fault occurs GDB will drop back to its prompt and it will be almost the same as running GDB with a core file. The major difference is there are some things you cannot do/print with a core file that you can when the program has crashed inside of GDB. (You can use print to call some functions inside the program, for example.)

您还可以使用 gdb --pid <the programs pid> 附加到已经运行的程序.

You can also attach to an already running program using gdb --pid <the programs pid>.

无论是使用核心文件还是使用上述方法之一,当您在崩溃后出现 GDB 提示时,键入 backtrace(或简称 bt)和 GDB将显示崩溃时的堆栈,包括每次调用的文件名和行号以及当前执行的行.

Either with a core file or with one of the methods above, when you have the GDB prompt after the crash, type backtrace (or bt for short) and GDB will show you the stack at the time of the crash, including the file names and line numbers of each call and the currently executing line.

这篇关于如何使用 GDB 从多个文件中找到分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆