Chinaunix首页 | 论坛 | 博客
  • 博客访问: 400373
  • 博文数量: 103
  • 博客积分: 3073
  • 博客等级: 中校
  • 技术积分: 1078
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-23 15:04
文章分类

全部博文(103)

文章存档

2012年(13)

2011年(76)

2010年(14)

分类: C/C++

2010-04-21 13:26:46

A segmentation fault (often shortened to segfault) or access violation is a particular error condition that can occur during the operation of . A segmentation fault occurs when a program attempts to access a 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 location, or to overwrite part of the ).

is one approach to and protection in the operating system. It has been superseded by 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 operating systems, a process that accesses an invalid memory address receives the . On , a process that accesses invalid memory receives the STATUS_ACCESS_VIOLATION .


Example

Here is an example of code that should create a segmentation fault on platforms with memory protection:

 int main(void)
{
char *s = "hello world";
*s = 'H';
}

When the program containing this code is , the "hello world" is placed in the section of the program binary marked as read-only; when loaded, the operating system places it with other strings and data in a read-only segment of memory. When executed, a variable, s, is set to point to the string's location, and an attempt is made to write an H character through the variable into the memory, causing a segmentation fault. Compiling such a program with a compiler that does not check for the assignment of read-only locations at compile time, and running it on a Unix-like operating system produces the following :


Common causes

A few causes of segmentation fault can be summarized as follows,

  • attempt to execute a program that does not compile correctly. Note that most compilers will not output a given a compile-time error.
  • using uninitialized pointers
  • dereference NULL pointers
  • attempt to access memory the program does not own.
  • attempt to alter memory the program does not own ().

Generally, segmentation faults occur because: a pointer is either NULL, or points to random memory (probably never initialized to anything), or points to memory that has been freed/deallocated/"deleted".

e.g.

    char *p1 = NULL;           // Initialized to null, which is OK,
// (but cannot be dereferenced on many systems).
char *p2; // Not initialized at all.
char *p3 = new char[20]; // Great! it's allocated,
delete [] p3; // but now it isn't anymore.

Now, referencing any of these variables could cause a segmentation fault.

阅读(1297) | 评论(0) | 转发(0) |
0

上一篇:Latex 示例

下一篇:intel assembly and AT&T

给主人留下些什么吧!~~