Vijay Kumar R Zanvar <vijoeyz@hotmail.com> wrote:
> I have following 2 questions:
> * What is bus error?
> * How is it different from segmentation fault?
It's easier to understand bus errors when you take a look at assembler
programming. Often you have commands to access single bytes, two bytes
a once (often called a word) or 4 bytes (often call long). Thus you
may have e.g. commands to move data from or to a CPU register (or
between memory locations) like
MOVE.B source, dest // moves single byte
MOVE.W source, dest // moves two bytes at once
MOVE.L source, dest // moves four bytes at once
The compiler will of course try to use a single command if possible
since it's faster than having to move the several bytes individually.
So, if the size of an int on your machine is 4 bytes, it will usually
use the MOVE.L version to move int data .
But on some machines MOVE.L can only be used with memory addresses
that can be divided by 4. If you try use it (or the compiler creates
machine instructions that would do this) you get a bus error. And
it's often rather simple to get the compiler to do so, if you have
e.g.
char *buf = malloc( 100 );
int a = * ( int * ) ( buf + 13 );
This code is rather likely to result in a bus error on these kinds of
machines. On other architectues (like, for example, INTEL processors)
it only results in slower execution speed. That's often a problem
with code that doesn't take this into account, the program seems to
work flawlessly on an INTEL processor but on other architectures (SUN
with Solaris is a typical example, AFAIR) it fails with bus errors.
That's also why malloc() and friends always have to return properly
aligned memory - since malloc() don't know what you're going to use
the memory for it has to return memory starting at an address that
can be accessed with the instructions for the widest type on your
machine.
Also the necessity for padding bytes in structures is a direct result
of these alignment issues. On a machine with 4 byte integers you will
have (at least) three padding bytes betwen the 'x' and 'y' member in
a structure like
struct {
char x;
int y;
} my_struct;
because otherwise writing 'my_struct.y' would result in an unaligned
access, leading to a bus error.
Segmentation faults are something completely different. You get them
when you try to access memory that either does not exist or which you
have no permission to access.
Regards, Jens
--
_ _____ _____
| ||_ _||_ _| Jens.Toerring@physik.fu-berlin.de
_ | | | | | |
| |_| | | | | | http://www.physik.fu-berlin.de/~toerring
\___/ens|_|homs|_|oerring