A segmentation violation occurs when your program tries to access a memory address that it doesn't have permission to. This can be:
- Memory regions that haven't been allocated to the process at all
- Memory regions that are reserved for the kernel to use
- Memory regions whose protection does not include the operation you tried (e.g. writing to read-only memory).
This most often occurs when you try to dereference a pointer that hasn't been initialized properly. Except in special circumstances, the proper ways to initialize a pointer are:
- Taking the address of some other variable, e.g.
ptr = &var;
.
- Allocating dynamic memory:
malloc/realloc
in C, new
in C++
- Assigning it from some other pointer variable that has been initialized properly.
You can also add and subtract from valid pointers to get new pointers. This pointer will be valid so long as you stay within the size of the object that the pointer was originally derived from. However, if you go outsize these bounds, you may or may not get a segmentation violation. Most often, you'll just access some adjacent object in memory, causing program bugs but not a signal.
Initializing a pointer from a integer, e.g. int ptr = 10;
, does not have defined behavior, but in most implementations it just tries to use this virtual memory address. Since most operating systems use low-numbered addresses for the kernel, this will usually result in a segmentation violation error.