[vox-tech] what is a bus error

Ken Bloom vox-tech@lists.lugod.org
Tue, 8 Jan 2002 11:07:07 -0800


Bus errors are a platform dependant thing. They can be caused by problems such as the integer 
alignment error below, where the computer tries to read a long from a memory location 
where the processor does not like to find the first byte of a long. This program didn't 
cause a bus error on my own x86, however it did cause a bus error on one of the HPs in the CS 
lab.

#include <iostream>
using namespace std;

int main()
{
  char * x = new char[16]; // the first byte has suitable alignment for anything

  for (int t=0;t<16;t++) x[t]=t;

  cout << reinterpret_cast<long*> (x) << endl;
  cout << reinterpret_cast<long*> (x+1) << endl;
 
  long a = *(reinterpret_cast<long*> (x+1)); 
  // there are no guarantees about the alignment of the second byte of data
  // so we could get a bus error here

  cout << setbase(ios::hex) << a << endl;

  delete[] x;
  return 0;
}

Matt Roper <matt@mattrope.com> spoke thus:
> In my experience, a bus error is caused by the same type of problem as a
> segmentation fault (i.e. out of bounds memory access).  I once had an
> out of bounds memory access in a program I wrote and found that
> depending on how far out of bounds my access was, the error message
> would change between "segmentation fault" and "bus error" (this program
> was running under Solaris on a Sun machine).
> 
> I'm not certain why one message appears sometimes and the other at other
> times, but one possibility (a wild guess) is that since some
> architectures use part of the address space to represent IO devices
> instead of memory locations, the "Bus Error" message will occur if the
> illegal memory location falls in the IO device address range and a
> "Segmentation Fault" will occur if the illegal memory location falls in
> the memory range.  FWIW, I've never seen a bus error message on x86
> Linux, so maybe it doesn't happen on the x86 architecture or maybe it's
> just triggered differently.