linux编程之 Core Dump
1赞
发表于 2017/7/14 8:57:18
阅读(2174)
一、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.1Copyright (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的信息的时候。