Segmentation Fault

what is segmentation fault actually?
sometimes i found that.
Such an error usually occurs when you write (somtetimes read) memory that is not yours.

Typical example is out of bounds:
1
2
char x[2];
x[2] = '.'; // Note: valid indexes are 0 and 1 


Note that the error might not occur because some other memory is affected that is actually yours. Or it might crash later seemingly unrelated.

memory that is not yours.

what do you mean with that?
Well he just gave you a perfectly fine example of what he meant by that. I'll give another one.

1
2
int arr[10];
arr[233] = 3;

You've allocated memory (on the stack) for 10 integers, which you can access within that array. But you're trying to access a memory outside of the array, as you can see by the example. That memory is not yours.
Addressing an array element that is out of bounds may, but won't necessarily generate a segmentation fault. With a debug build, an out of bounds reference will generate a bounds trap. i.e. the runtime detects that the index is out of bounds and generates a trap to that effect.

As coder777 said, a segmentation fault occurs when you try to access memory that does not belong to your process. On a 32 bit machine, a 32 bit pointer can address 2GB of memory. When you run your program, you don't automatically get 2GB of memory assigned to your program. The operating system maps a certain number of pages of memory to your program. Some of those pages are read-only (code, constants), and some are read-write (data). Pages within that 2GB address spaces that are not mapped to you process are marked as "unavailable". If you try to access an an address in an unavailable page, or write to a read-only page, you will get a segmentation fault.
Topic archived. No new replies allowed.