Transfer from http://blog.csdn.net/todd911/article/details/8813321
Bus errors (core dumped) are mentioned in "C Expert programming".
Bus errors are almost always caused by misaligned reads or writes.
It is called a bus error because the blocked component is address bus when there is an unaligned memory access request. Alignment means that a data item can only be stored in a memory location where the address is an integer multiple of the size of the data item.
Modern computer architectures, especially RISC architectures, require word alignment because the extra logic associated with arbitrary alignment makes the memory system larger and slower.
By forcing each memory access to a single cache line or a separate page, you can greatly simplify (and accelerate) hardware such as the cache controller and memory management unit.
The size of the page and cache is carefully designed so that an atomic data item does not cross the boundary of a page or cache block as long as the alignment rules are adhered to.
Examples of bus errors are also given in the book:
[CPP]View Plaincopy
- Union
- {
- Char a[10];
- int i;
- }u;
- int *p = (int*) & (U.a[1]);
- *p = 17; An unaligned address in the/*p will cause a bus error because the union of the array and int ensures that a is aligned by 4 bytes of int, so "a+1" must not be aligned with int. */
However, this error does not occur in the actual operation, my environment is CentOS release 6.2,2.6.32-279.14.1.EL6.I686,GCC 4.4.6
Later on the online reference to a sample program, the program is modified as follows:
[CPP]View Plaincopy
- #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 results of the operation are as follows:
Bus error (Core dumped)
The reasons are:
The x86 architecture aligns the addresses, accesses two times, and then puts the first tail and the second head together.
If it were not for x86, the machine under that architecture would not automatically do the work, and it would produce a core.
If the alignment check function is turned on in the code, the bus error will be displayed after running
Bus error (Fieldbus errors)