Blog Archive

Segmentation Fault and Bus Error

Segmentation Fault

Wikipedia Page : http://en.wikipedia.org/wiki/Segmentation_fault

A segmentation fault occurs when your program tries to access memory locations that haven't been allocated for the program's use. Here are some common errors that will cause this problem:

scanf("%d", number);

In this case, number is integer. scanf() expects you to pass it the address of the variable you want to read an integer into. But, the writer has fogotten to use the `&' before number to give scanf the address of the variable. If the value of number happened to be 3, scanf() would try to access memory location 3, which is not accessible by normal users. The correct way to access the address of number would be to place a `&' (ampersand) before number:

scanf("%d", &number);

Another common segmentation fault occurs when you try to access an array index which is out of range. Let's say you set up an array of integers:

int integers[80];

If, in your program, you try to use an index (the number within the brackets) over 79, you will ``step out of your memory bounds'', which causes a segmentation fault. To correct this, rethink your array bounds or the code that is using the array.











Bus Error

Wikipedia Page : http://en.wikipedia.org/wiki/Bus_error

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A SIGBUS is often caused by accessing data at an address that is not aligned to
a multiple of the width of the data. A 4 byte int must be aligned on a multiple
of 4. An 8 byte long must be aligned on a multiple of 8.

(processor) bus error - A fatal failure in the execution of a machine language
instruction resulting from the processor detecting an anomalous condition on its
bus. Such conditions include invalid address alignment (accessing a multi-byte
number at an odd address), accessing a physical address that does not correspond
to any device, or some other device-specific hardware error. A bus error
triggers a processor-level exception which Unix translates into a "SIGBUS"
signal which, if not caught, will terminate the current process.

From Cisco documentation
The system encounters a bus error when the processor tries to access a memory
location that either does not exist (a software error) or does not respond
properly (a hardware problem).


What is the difference between a Bus Error and a Segmentation Error?

Full Article:

Both are addressing errors, such as trying to address memory outside of your
legal address space. A segmentation error is detected by the kernel, while a
bus error is detected by the hardware.

These errors will occur when the program tries to access a memory location
outside its address space. That is, accessing uninitilized pointers, or even
mangled pointers (ones which have no reference or have been deleted).

The Bus error means that the kernel did not detecet the problem on its own;
the memory system realized the error.

No comments: