What is segmentation fault?

7

This error often occurs with faulty codes. I do not see it occurring in other languages. Why does it occur? What does it mean?

    
asked by anonymous 13.01.2017 / 11:31

1 answer

9

This occurs by accessing an unauthorized memory point for your application.

When your application is running the operating system releases access to virtual memory. Contrary to what many people think, you do not have access to physical memory (RAM) directly, in fact it may not even be in RAM. It is a problem of the operating system to place where it wants. It's a problem for him to organize the memory however he wants. It will put your code, static data area, stack and then will allocate other stretches dynamically as needed, the heap . Physical memory is not usually in sequence, but it seems to be. When your application accesses it seems that the whole memory of the computer is hers, so it's called virtual memory, the addresses are not the physical ones. Of course the memory needs to be reserved for your use.

So any address that is accessed by the application and was not reserved is considered an invalid address. So there is a protection to the other applications. Memory is divided into segments, so attempting to access a segment that does not belong to it causes a segmentation fault.

In C or C ++ it is common to have this type of problem because the use of the pointers is very free and direct. It is relatively easy to make a pointer variable have an invalid value. Mainly for forget to initialize pointer , but also:

  • by doing wrong arithmetic or wild pointer ),
  • treat other data as if it were a pointer,
  • use an address that was existing and is no longer dangling pointer
  • ),
  • Overflow stack ,
  • access address in addition to an array , which in other languages is the out of range , especially in string
  • modify static area, especially literals strings ,
  • among others.

A segmentation fauult is very common because of a undefined behavior left in the code.

But do you know which address most causes this problem? It's 0, meaning the null . At this point it is the same as the Null Pointer or Null Reference exception of other languages. These languages are not so liberal with the use of pointers, they usually manage access to memory, but they usually allow an object to be null. More modern languages are avoiding this and only letting the null occur by choosing the programmer where it makes sense.

Compilers today have options to help identify potential pointer problems, and do not let them do operations that will create problems. There are extra tools that help even more.

When this error appears, start to see its pointers, the problem is in one of them.

    
13.01.2017 / 11:31