在Linux环境下执行程序的时候,有的时候会出现段错误(‘segment fault’),同时显示core dumped,就像下面这样:
[1] 15428 segmentation fault (core dumped) ./a.out
下面是我网上找到的段错误的定义和说明:
A segmentation fault (often shortened to segfault) is a particular
error condition that can occur during the operation of computer
software. In short, a segmentation fault occurs when a program
attempts to access a memory location that it is not allowed to access,
or attempts to access a memory location in a way that is not allowed
(e.g., attempts to write to a read-only location, or to overwrite part
of the operating system). Systems based on processors like the
Motorola 68000 tend to refer to these events as Address or Bus errors.Segmentation is one approach to memory management and protection in
the operating system. It has been superseded by paging for most
purposes, but much of the terminology of segmentation is still used,
“segmentation fault” being an example. Some operating systems still
have segmentation at some logical level although paging is used as the
main memory management policy.On Unix-like operating systems, a process that accesses invalid memory
receives the SIGSEGV signal. On Microsoft Windows, a process that
accesses invalid memory receives the STATUS_ACCESS_VIOLATION
exception.
简单理解就是访问了不该访问的内存就会产生段错误。
而core dump是一种将出错时的调用堆栈等信息写入到一个文件中,方便后面调试。Ubuntu下需要进行一些设置才能正确地调试core dump,下面是详细的说明。
ulimit 设置
ulimit是对shell启动进程所占系统资源进行限制的一个工具,详细的使用说明可以看这里。在这里我们需要对ulimit进行设置,因为在Ubuntu下,默认的core 文件的大小是0,可以通过执行ulimit -a查看所有的选项设置值:
$ ulimit -a
-t: cpu time (seconds) unlimited
-f: file size (blocks) unlimited
-d: data seg size (kbytes) unlimited
-s: stack size (kbytes) 8192
-c: core file size (blocks) 0
-m: resident set size (kbytes) unlimited
-u: processes 2063144
-n: file descriptors 1024
-l: locked-in-memory size (kbytes) 64
-v: address space (kbytes) unlimited
-x: file locks unlimited
-i: pending signals 2063144
-q: bytes in POSIX msg queues 819200
-e: max nice 0
-r: max rt priority 0
-N 15: unlimited
可以看到上面的结果中-c: core file size (blocks) 那项的值是0,因此在段错误发生core dump的时候,默认也不会生成core文件。
那应该怎么修改core文件的大小呢?ulimit的值都可以通过ulimit -k v的形式来设置,其中-k就是上面结果中的第一列,而v就是设置的值,最大可以设置为unlimited,所以我们可以这样来设置:
ulimit -c unlimited
注意:新开一个Shell的时候,ulimit选项都恢复了默认选项,需要重新设置该值