How to get a “bus error”?

2019-02-16 07:19发布

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?

标签: c++ bus-error
12条回答
乱世女痞
2楼-- · 2019-02-16 07:46
int main(int argc, char **argv)
{
    char *bus_error = new char[1];
    for (int i=0; i<1000000000;i++) {
        bus_error += 0xFFFFFFFFFFFFFFF;
    *(bus_error + 0xFFFFFFFFFFFFFF) = 'X';
    }
}

Bus error: 10 (core dumped)

查看更多
Animai°情兽
3楼-- · 2019-02-16 07:46

Simple, write to memory that isn't yours:

int main()
{
    char *bus_error = 0;

    *bus_error = 'X';
}

Instant bus error on my PowerPC Mac [OS X 10.4, dual 1ghz PPC7455's], not necessarily on your hardware and/or operating system.

There's even a wikipedia article about bus errors, including a program to make one.

查看更多
闹够了就滚
4楼-- · 2019-02-16 07:47

Bus errors can only be invoked on hardware platforms that:

  1. Require aligned access, and
  2. Don't compensate for an unaligned access by performing two aligned accesses and combining the results.

You probably do not have access to such a system.

查看更多
爷的心禁止访问
5楼-- · 2019-02-16 07:47

For 0x86 arch:

#include <stdio.h>

int main()
{
#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
#endif

    int b = 0;
    int a = 0xffffff;
    char *c = (char*)&a;
    c++;
    int *p = (int*)c;
    *p = 10;  //Bus error as memory accessed by p is not 4 or 8 byte aligned
    printf ("%d\n", sizeof(a));
    printf ("%x\n", *p);
    printf ("%x\n", p);
    printf ("%x\n", &a);
}

Note:If asm instructions are removed, code wont generate the SIGBUS error as suggested by others. SIGBUS can occur for other reason too.

查看更多
老娘就宠你
6楼-- · 2019-02-16 07:51

Try something along the lines of:

#include <signal.h>
int main(void)
{
    raise(SIGBUS);
    return 0;
}

(I know, probably not the answer you want, but it's almost sure to get you a "bus error"!)

查看更多
Root(大扎)
7楼-- · 2019-02-16 07:56

How about this? untested.

  #include<stdio.h>

    typedef struct
    {
    int a;
    int b;
    } busErr;

    int main()
    {
    busErr err;
    char * cPtr;
    int *iPtr;
    cPtr = (char *)&err;
    cPtr++;
    iPtr = (int *)cPtr;
    *iPtr = 10;
    } 
查看更多
登录 后发表回答