linux上一个经典的segmentation fault

废话不多说,请看下面代码:

#include<string>
#include<stdio.h>
#include<unistd.h>
#include<string.h>
int version=1;

int main()
{
	char *testarry[3]={"a","b","c"};
	strcpy(testarry[2],"C");
	printf("%c",testarry[2][0]);
	printf("%s\n",testarry[2]);
	if(testarry[2][0])
	{
	printf("version:%d",1);
	}
	return 0;
}

编译运行,segmentation fault 出现了。分析以上代码,一眼看上去,似乎没毛病,尝试把下面语句去掉
strcpy(testarry[2],“C”);

竟然运行通过,也就说使用testarry[2][0]作为if判断的标准,作为%c输出都没有问题。

那么奇怪了啊,为什么strcopy语句一加上就挂呢。搞出gdb来分析。
使用g++ main.cpp -g编译得到a.out -g是为了得到符号表
过程如下:
yuneec01@yuneec01:~/testcplus$ gdb a.out
GNU gdb (Ubuntu 7.11.1-0ubuntu1~16.5) 7.11.1
Copyright © 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 “show copying”
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 a.out…done.
(gdb) list
1 #include
2 #include<stdio.h>
3 #include<unistd.h>
4 #include<string.h>
5
6 //#include “dervied.h”
7 int version=1;
8
9 int main()
10 {
(gdb) list
11 char *testarry[3]={“a”,“b”,“c”};
12 strcpy(testarry[2],“C”);
13 printf("%c",testarry[2][0]);
14 printf("%s\n",testarry[2]);
15 if(testarry[2][0])
16 {
17 printf(“version:%d”,1);
18 }
19 return 0;
20 }
(gdb) break 11
Breakpoint 1 at 0x40063d: file main.cpp, line 11.
(gdb) r
Starting program: /home/yuneec01/testcplus/a.out

Breakpoint 1, main () at main.cpp:11
11 char *testarry[3]={“a”,“b”,“c”};
(gdb) n
12 strcpy(testarry[2],“C”);
(gdb) n

Program received signal SIGSEGV, Segmentation fault.//这里就挂了
0x0000000000400659 in main () at main.cpp:12
12 strcpy(,“C”);
(gdb) p testarry //果断把testarry的打出来看看,看到testarry[2]的地址是0x400748
$1 = {0x400744 “a”, 0x400746 “b”, 0x400748 “c”}

也就是操作这个地址挂了
我们去read以下a.out看看
使用readelf -S a.out
找0x400748所在的段,如下:
[16] .rodata PROGBITS 0000000000400740 00000740
0000000000000015 0000000000000000 A 0 0 4
问题出现,此段为.rodata

strcpy把rodata当作目标字符串操作,setmentation fault是必然出现了。

以上给大家班门弄斧的展示了一次寻找segmentation fault根源的方法。水平有限,还望赐教。
谢谢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值