C 程式發生 Segmentation fault 時,若啟用 core dump,核心會將記憶體映像寫入磁碟供事後除錯。
ulimit -a # 查看目前限制 (core file size 通常為 0)
ulimit -c 0 # 禁止產生 core
ulimit -c 100 # 限制 100 KB
ulimit -c unlimited # 無限制 (建議開發環境啟用)
永久生效:將 ulimit -c unlimited 加入 /etc/bashrc 或 ~/.bashrc。
可透過 /proc/sys/kernel/core_pattern 自訂 core 檔名格式 (如 core.%e.%p.%t),詳見 man 5 core。
// a.c
#include <stdio.h>
int main() {
char *ptr = "linuxers.cn";
*ptr = 0; // 寫入唯讀區段 → Segfault
}
$ gcc -g -o test a.c
$ ./test
段錯誤
$ ulimit -c unlimited
$ ./test
段錯誤 (core dumped)
$ ls -l core.*
-rw------- 1 user user 139264 ... core.2065
$ gdb ./test core.2065
...
Core was generated by `./test'.
Program terminated with signal 11, Segmentation fault.
#0 0x0804836f in main () at a.c:6
6 *ptr = 0;
精確定位到第 6 行寫入字串常數區導致錯誤。核心傾印是開發階段定位記憶體錯誤的利器。