views:

105

answers:

2

In Linux:

What is a segmentation fault? I know it crashes programs, but is that some sort of memory leak problem, or something completely unrelated? Also, how do you deal with these? Is this typically a problem with the computer set-up, or within the application itself?

Also, does this happen in other OS's as well?\

Thanks!

+3  A: 

A segmentation fault is when your program attempts to access memory it has either not been assigned by the operating system, or is otherwise not allowed to access.

"segmentation" is the concept of each process on your computer having its own distinct virtual address space. Thus, when Process A reads memory location 0x877, it reads information residing at a different physical location in RAM than when Process B reads its own 0x877.

All modern operating systems support and use segmentation, and so all can produce a segmentation fault.

To deal with a segmentation fault, fix the code causing it. It is generally indicative of poor programming, especially boundary-condition errors, incorrect pointer manipulation, or invalid assumptions about shared libraries. Sometimes segfaults, like any problem, may be caused by faulty hardware, but this is usually not the case.

Borealid
Segmentation faults are independent from virtual address spaces.
Porges
As I explained, the very name "segmentation" fault comes from distinct virtual address spaces. Context switches would be prohibitively expensive in a realm where applications made use of physical addresses without translation. The concepts are inextricably intertwined.
Borealid
@Borealid: I believe Porges was referring to the fact that segmentation faults can also occur when you're trying to write read-only memory for example, which is actually a feature unrelated to virtual memory.
Dean Harding
Yes, correct, you get a segfault when accessing memory protected via mprotect() or by the operating system directly, etc etc. My first line was explaining what a segfault *is*. The next lines try to explain *why* and *how*. Perhaps I should have been less verbose.
Borealid
I didn't mean to say you're bluntly wrong just that the concept isn't dependent upon that :) Maybe I should have written a longer sentence...
Porges
A: 

A 'segfault' is when a program accesses protected or invalid memory; usually due to poor memory management or buggy pointer manipulation.

The OS detects invalid memory access and crashes the app.

John Weldon