Bus errors VS Segmentation faults

Bus errors are rare nowadays on x86 and occur when your processor cannot even attempt the memory access requested, typically:

using a processor instruction with an address that does not satisfy its alignment requirements.

Segmentation faults occur when accessing memory which does not belong to your process, they are very common and are typically the result of:

using a pointer to something that was deallocated.
using an uninitialized hence bogus pointer.
using a null pointer.
overflowing a buffer.

PS: To be more precise this is not manipulating the pointer itself that will cause issues, it’s accessing the memory it points to (dereferencing).

They aren’t rare; I’m just at Exercise 9 from How to Learn C the Hard Way and already encountered one…

Another cause of bus errors (on Linux anyway) is when the operating system can’t back a virtual page with physical memory (e.g. low-memory conditions or out of huge pages when using huge page memory.) Typically mmap (and malloc) just reserve the virtual address space, and the kernel assigns the physical memory on demand (so called soft page faults.) Make a large enough malloc, and then write to enough of it and you’ll get a bus error.

A segfault is accessing memory that you’re not allowed to access. It’s read-only, you don’t have permission, etc…

A bus error is trying to access memory that can’t possibly be there. You’ve used an address that’s meaningless to the system, or the wrong kind of address for that operation.

在《C专家编程》中提到了总线错误bus error(core dumped)。
参考: http://www.voidcn.com/article/p-pbirlrnm-bew.html

#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

                char a[10];
                int i;

        int *p =(int*)&(u.a[1]);
        *p =17;


  1. Bus errors —— 当前程序无法获取到所需要的内存》》饿死
  2. Segmentation faults —— 访问的内存不属于当前程序所分配的内存空间》》非法访问他人空间被毙