linux中出现segmentation fault错误

自己写程序的时候遇到这个问题很多次,大部分都是指针没有动态分配空间就直接使用下标造成的。

比如:

char *s;

cin>>s;

int len=strlen(s);

for(int i=0;i<len;i++)  s[i]....

 

出现过这个错误几次之后我就会深刻的记住如果是指针,没有指向数组,就要用malloc之类的函数分配空间。

char *s;

s=(char *)malloc(sizeof(char)*100);

cin>>s;

int len=strlen(s);

for(int i=0;i<len;i++)  s[i]....

 

 

或者用指针直接指向数组,不过感觉没什么意义。。

char s[100];

char *p;

cin>>s;

p=s;

int len=strlen(s);

for(int i=0;i<len;i++)  p[i]....

 

 

找了一篇关于linux下出现段错误原因的文章:

 

 

Segmentation Fault in Linux
1
Segmentation Fault in Linux
—— 原因与避免
Author: ZX_WING(xing5820@163.com)
Segmentation Fault in Linux
2
写在前面的话
最近CU(chinaunix)出现了很多问segmentation fault
的帖子,其实这也是个“月经贴”了,泡CU 几年,每个月
都有人问。为了减少重复回帖,笔者结合自己的经验,总结
了SIGSEGV 在Linux 中产生的机理,并用实际例子概括哪
些编程错误容易引发SIGSEGV。由于本人经验有限,文中
难免有疏漏和错误,请发现的朋友发信到xing5820@163.com
指正,笔者好即使修改。
(版权声明:本文欢迎转载,但未经允许不得用于商业目的)
Segmentation Fault in Linux
3
内容提要
本文简单介绍了Segmentation fault 发生的原因,结合实
际例子描述了内核向用户态程序发送SIGSEGV 信号的流
程。文中以实例回答了常见的一些SIGSEGV 问题,例如“为
什么函数返回了栈还可以访问?”、“为什么free()后的内存
仍然可以使用”、“为什么我遇到的是SIGSEGV 而不是
SIGILL 信号”等。最后笔者结合自己的经验,列举了一些预
防SIGSEGV 的编程习惯,供大家参考。SIGSEGV 严格依赖
操作系统、编译器、硬件平台,本文基于Linux、GCC、32bit
IA32 架构,但对其他平台操作系统也有借鉴意义。
Segmentation Fault in Linux
4
Revision History
日期版本描述
2009.12.21 1.0 初次发表版本
Segmentation Fault in Linux
5
1.什么是“Segmentation fault in Linux”?
我们引用wiki 上的一段话来回答这个问题。
A segmentation fault (often shortened to SIGSEGV) is a particular
error condition that can occur during the operation of computer
software. 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
(for example, attempting to write to a read-only location, or to
overwrite part of the operating system).
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 an invalid
memory address receives the SIGSEGV signal. On Microsoft Windows, a
process that accesses invalid memory receives the
STATUS_ACCESS_VIOLATION exception.
上述文字没有给出SIGSEGV 的定义,仅仅说它是“计算机软件操作过程中的一种错误
情况”。文字描述了SIGSEGV 在何时发生,即“当程序试图访问不被允许访问的内存区域
(比如,尝试写一块属于操作系统的内存),或以错误的类型访问内存区域(比如,尝试写
一块只读内存)。这个描述是准确的。为了加深理解,我们再更加详细的概括一下SIGSEGV。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值