Bus Error (core dumped) is mentioned in Expert C programming ).
Bus errors are almost all caused by unaligned reads or writes.
It is called a bus error because the blocked component is the address bus when an unaligned memory access request occurs. Alignment means that data items can only be stored in the memory location where the address is an integer multiple of the data item size.
Word Alignment is required in the modern computer architecture, especially the RISC architecture, because additional logic related to any alignment will make the memory system larger and slower.
By forcing each memory access to a single cache row or a single page, you can greatly simplify (and accelerate) hardware such as the cache controller and Memory Management Unit.
The page size and cache size are carefully designed so that as long as the alignment rules are followed, an atomic data item cannot cross the boundary of a page or cache block.
The following is an example of a bus error:
Union {char a [10]; int I;} U; int * P = (int *) & (U. A [1]); * P = 17;/* unaligned addresses in P may cause bus errors, because the combination of the array and INT ensures that A is aligned according to the four bytes of the int, "A + 1" is certainly not aligned by the int. */
However, this error does not occur during actual running. My environment is centos Release 6.2, 2.6.32-279.14.1.el6.i686, GCC 4.4.6
Later, I referred to a sample program on the Internet and changed the program to the following:
#include <stdlib.h>int main(int argc, char **argv) {#if defined(__GNUC__)# if defined(__i386__) /* Enable Alignment Checking on x86 */ __asm__("pushf\norl $0x40000,(%esp)\npopf");# elif defined(__x86_64__) /* Enable Alignment Checking on x86_64 */ __asm__("pushf\norl $0x40000,(%rsp)\npopf");# endif#endif union{ char a[10]; int i; }u; int *p =(int*)&(u.a[1]); *p =17;}
The running result is as follows:
Bus Error (core dumped)
The reason is:
The X86 architecture alignment the address, access twice, and then combine the first tail and the second header.
If it is not x86, the machines in the architecture will not automatically perform this job, and the core will be generated.
If the alignment check function is enabled in the code, a bus error is displayed after running.