Today, segmentation fault appeared when I was writing a program. I checked some information on the Internet, basically because of illegal memory access.
For example, if the array is out of bounds, the control of the cyclic variable during loop operations may also cause the overflow of the length during string copy, the pointer points to an invalid space, and a pointer is declared, however, if you do not initialize it, You can directly reference it, or release the memory without opening up the memory space. Here are some possible situations you may find. Just remind yourself.
1. Memory Access out of bounds
A) array access is out of bounds due to incorrect subscript.
B) when searching for a string, the string Terminator is used to determine whether the string ends, but the string does not use the terminator normally.
C) use strcpy, strcat, sprintf, strcmp, strcasecmp, and other string operation functions to read/write the target string. Functions such as strncpy, strlcpy, strncat, strlcat, snprintf, strncmp, and strncasecmp should be used to prevent read/write from being out of bounds.
D) access to the system data zone, especially write data to the System-protected memory address, and access to areas outside your memory (array out-of-bounds, inconsistent variable types, etc.
2. multi-threaded programs use functions with unsafe threads.
3. data read and write with multiple threads is not locked. For global data that will be accessed by multiple threads at the same time, pay attention to lock protection, otherwise it will easily cause core dump
4. Invalid Pointer
A) Use a null pointer.
B) Use Pointer conversion at will. A pointer pointing to a memory segment, unless it is determined that the memory is originally allocated to a structure or type, or an array of this structure or type, otherwise, instead of converting it to a pointer of this structure or type, you should copy this memory to a structure or type and then access this structure or type. This is because if the starting address of this memory segment is not aligned according to this structure or type, it is easy to access it because of Bus Error and core dump.
5. Stack Overflow. Do not use large local variables (because all local variables are allocated on the stack). This can easily cause stack overflow, damage the stack and heap structure of the system, and cause inexplicable errors.
Another problem is that there will be such information during debugging: Program terminated with signal SIGSEGV, segmentation fault.
The SIGSEGV signal is often associated with the sigbus signal,
The differences between sigbus and SIGSEGV signals are as follows:
1) sigbus (Bus Error) means that the address corresponding to the pointer is a valid address, but the bus cannot use the pointer normally.
This is usually caused by unaligned data access.
2) SIGSEGV (segment fault) means that the address corresponding to the pointer is invalid and there is no physical memory pair.