/home/tnishinaga/TechMEMO

日々行ったこと、面白かったことを書き留めます。

Linuxでcoredumpを吐く

C言語でメモリ関連のバグを作ったときは普通coredumpを読んで調べて行くみたいだけれど、私の環境ではなぜかcoredumpが出ませんでした。

調べて見ると、最近のLinuxではulimitで設定しないとcoredumpを吐いてくれないらしい。

というわけで設定してみる。

$ ulimit -c unlimited

以上で無制限にコアダンプをとるようになる。

確認のため、以下のプログラムを動かしてみる。

#include <stdio.h>
#include <stdint.h>

int main(void){
  printf("%d\n", *(int *)0x00);
  return 0;
}

上記のコードはNULLを参照するので、ここでセグフォが起きる。

以下のコマンドでコンパイルして、実行してみる。

$ gcc -g -std=c99 main.c
$ ./a.out
Segmentation fault (コアダンプ)
$ ls
a.out  core  main.c

セグフォの後にcoreというファイルができる。これがcoredump。

こいつを以下の様にgdbで読み込むと、エラーの場所が表示される。

$ gdb ./a.out core 
GNU gdb (GDB) 7.4.1-debian
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home/toshifumi/src/coredump/a.out...done.
[New LWP 4455]

warning: Can't read pathname for load map: Input/output error.
Core was generated by `./a.out'.
Program terminated with signal 11, Segmentation fault.
#0  0x0000000000400515 in main () at main.c:5
5     printf("%d\n", *(int *)0x00);

これでデバッグが捗る……もう1stepずつ実行するとかアホなことしなくていいんだ……よかった……よかった……