linux编程之 Core Dump

一、Core Dump 定义

Core Dump 又叫核心转存。当程序在运行过程中发生异常,这时Linux系统可以把程序出错的内存内容存储在一个core文件中,这种过程叫 core Dump。

CoreDump 主要用来对付什么样的错误呢?

Segment fault

Linux 应用程序在运行过程中,经常会遇到Segment fault(段错误)这样的错误。产生这样的错误的原因有:


  • 数组访问越界
  • 访问空指针
  • 栈溢出
  • 修改只读内存
  • ......

1.1、CoreDump 使能

在Linux系统中,默认是关闭core dump功能的,但是可以使用ulimit命令打开/关闭 core dump 功能。

ulimit -c unlimited   //打开
ulimit -c 0           //关闭

1.2、Core 文件分析

发生core dump之后,可以使用gdb进行查看core文件的内容,以定位程序出错的位置。

用法:
gdb 程序名 core文件名
例子:
gdb ./test test.core

二、使用范例(访问空指针)

先编写如下程序:test.c

#include <stdio.h>
#include <malloc.h>
#include <string.h>

void main()
{
    char * a = NULL;
    char * b = (char *)malloc(100);
    
    strcpy(b,"value b");
    printf("value b is : %s \n",b);
    printf("value a is : %d \n",*a);
    
    strcpy(a,"value a");
    
    free(a); free(b);
}

使用编译器编译,并运行:

gcc -o test -g test.c
./test

控制台输出如下:

value b is : value b 
Segmentation fault (core dumped)

这时候使用gdb进行调试:

gdb ./test ./core 

输出如下:

GNU gdb (Ubuntu 7.11.1-0ubuntu1~16.04) 7.11.1
Copyright (C) 2016 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 "showopying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./test...done.
[New LWP 3789]
Core was generated by `./test'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0  0x00000000004005ff in main () at test.c:12
12          printf("value a is : %d \n",*a);
(gdb) 

这里可以看出GDB 给出了发生core dump时候的函数具体位置在 test.c 的12 行。这里打印a的信息的时候。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在Linux下程序不寻常退出时,内核会在当前工作目录下生成一个core文件(是一个内存映像,同时加上调试信息)。使...
    随风化作雨阅读 47,626评论 2 15
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,720评论 19 139
  • 工具:GDB 分析 导致进程异常退出的这两类情况: 第一类:向进程发送信号导致进程异常退出; 第二类:代码错误导致...
    董春磊阅读 5,974评论 0 1
  • 引文 4月份的时候看到一道面试题,据说是腾讯校招面试官提的:在多线程和高并发环境下,如果有一个平均运行一百万次才出...
    helloworlds阅读 5,457评论 1 12
  • 从去年下半年开始,我们家的小小马就开始上幼儿园了,这一年多全是他外公和外婆在带,1月17日下午,幼儿园刚放...
    夏所珍创作室阅读 2,833评论 0 2