【mac】Mac OS 产生 Coredump,定位 Segmentation Fault

【mac】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,但是没有对这个指针分配地址,而直接使用了指针,导致程序奔溃。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值