How to get a "bus error"?

Lazer picture Lazer · Jan 15, 2010 · Viewed 14.9k times · Source

I am trying very hard to get a bus error.

One way is misaligned access and I have tried the examples given here and here, but no error for me - the programs execute just fine.

Is there some situation which is sure to produce a bus error?

Answer

ephemient picture ephemient · Jan 15, 2010

This should reliably result in a SIGBUS on a POSIX-compliant system.

#include <unistd.h>
#include <stdio.h>
#include <sys/mman.h>
int main() {
    FILE *f = tmpfile();
    int *m = mmap(0, 4, PROT_WRITE, MAP_PRIVATE, fileno(f), 0);
    *m = 0;
    return 0;
}

From the Single Unix Specification, mmap:

References within the address range starting at pa and continuing for len bytes to whole pages following the end of an object shall result in delivery of a SIGBUS signal.