Mac OS 产生 Coredump,定位 Segmentation Fault

前期工作

开启 Mac Coredump

% sudo sysctl kern.coredump=1
kern.coredump: 1 -> 1

设置 /cores 目录属性

$ sudo mkdir /cores 
$ sudo chown root:admin /cores 
$ sudo chmod 1775 /cores
$ sudo chmod o+w /cores

设置 core 文件大小

$ ulimit -c unlimited

定位 Segmentation Fault

测试代码

#include <cstdio>
#include <cstdlib>
int main() {
	int *ptr=NULL;
	*ptr=0;
	return 0;
}

编译

$ g++ -g test.cpp -o test

产生 Coredump

% ./test


zsh: segmentation fault (core dumped)  ./test
% ls -lh /cores 
total 4262432
-r--------  1 yeecall  wheel   2.0G  9  8 00:14 core.37676

我们可以看到在 /cores 目录下,产生了一个 core.37676 的 coredump 文件。

调试 core 文件

我们使用 lldb 进行调试。命令如下:

% lldb -c /cores/core.37676
(lldb) target create --core "/cores/core.37676"
Core file '/cores/core.37676' (x86_64) was loaded.
(lldb)

这样,我们就打开了 core.37676 文件,准备进行调试。输入 bt 进行跟踪。

% lldb -c /cores/core.37676
(lldb) target create --core "/cores/core.37676"
Core file '/cores/core.37676' (x86_64) was loaded.
(lldb) bt
* thread #1, stop reason = signal SIGSTOP
  * frame #0: 0x0000000108e1efa9 test`main at test.cpp:5:6
    frame #1: 0x00007fff72df2cc9 libdyld.dylib`start + 1

上面的 LOG 可以看到,定位在 test.cpp 的第 5 行,参考 test.cpp 的源码,我们可以发现 Segmentation Fault 的语句如下:

	*ptr=0;

因为我们只是定义了一个指针 ptr,但是没有对这个指针分配地址,而直接使用了指针,导致程序奔溃。

猜你喜欢

转载自blog.csdn.net/justidle/article/details/108459488