What is a bus error?

2019-01-01 08:03发布

What does the "bus error" message mean, and how does it differ from a segfault?

15条回答
唯独是你
2楼-- · 2019-01-01 08:25

I agree with all the answers above. Here are my 2 cents regarding the BUS error:

A BUS error need not arise from the instructions within the program's code. This can happen when you are running a binary and during the execution, the binary is modified (overwritten by a build or deleted etc.).

Verifying if this is the case: A simple way to check if this is the cause is by launching running instances of the same binary and to run a build. Both the running instances would crash with a SIGBUS error shortly after the build has finished and replaced the binary (the one that both the instances are currently running)

Underlying Reason: This is because OS swaps memory pages and in some cases the entire binary might one be in memory and these crashes would occur when the OS tries to fetch the next page from the same binary, but the binary has changed since it last read it.

查看更多
初与友歌
3楼-- · 2019-01-01 08:27

I just found out the hard way that on an ARMv7 processor you can write some code that gives you a segmentation fault when unoptimized, but gives you a bus error when compiled with -O2 (optimize more). I am using gcc arm gnueabihf cross compiler from ubuntu x64.

查看更多
弹指情弦暗扣
4楼-- · 2019-01-01 08:28

A specific example of a bus error I just encountered while programming C on OS X:

#include <string.h>
#include <stdio.h>

int main(void)
{
    char buffer[120];
    fgets(buffer, sizeof buffer, stdin);
    strcat("foo", buffer);
    return 0;
}

In case you don't remember the docs strcat appends the second argument to the first by changing the first argument(flip the arguments and it works fine). On linux this gives a segmentation fault(as expected), but on OS X it gives a bus error. Why? I really don't know.

查看更多
查无此人
5楼-- · 2019-01-01 08:30

My reason for bus error on Mac OS X was that I tried to allocate about 1Mb on the stack. This worked well in one thread, but when using openMP this drives to bus error, because Mac OS X has very limited stack size for non-main threads.

查看更多
谁念西风独自凉
6楼-- · 2019-01-01 08:31

You can also get SIGBUS when a code page cannot be paged in for some reason.

查看更多
浮光初槿花落
7楼-- · 2019-01-01 08:32

It normally means an un-aligned access.

An attempt to access memory that isn't physically present would also give a bus error, but you won't see this if you're using a processor with an MMU and an OS that's not buggy, because you won't have any non-existent memory mapped to your process's address space.

查看更多
登录 后发表回答