I had a bug in my code that went like this.
char desc[25];
char name[20];
char address[20];
sprintf (desc, "%s %s", name, address);
Ideally this should give a segfault. However, I saw this give a bus error.
Wikipedia says something to the order of ‘Bus error is when the program tries to access an unaligned memory location or when you try to access a physical (not virtual) memory location that does not exist or is not allowed. ‘
The second part of the above statement sounds similar to a seg fault. So my question is, when do you get a SIGBUS and when a SIGSEGV?
EDIT:-
Quite a few people have mentioned the context. I’m not sure what context would be needed but this was a buffer overflow lying inside a static class function that get’s called from a number of other class functions. If there’s something more specific that I can give which will help, do ask.
Anyways, someone had commented that I should simply write better code. I guess the point of asking this question was “can an application developer infer anything from a SIGBUS versus a SIGSEGV?” (picked from that blog post below)
As you probably realize, the base cause is undefined behavior in your
program. In this case, it leads to an error detected by the hardware,
which is caught by the OS and mapped to a signal. The exact mapping
isn’t really specified (and I’ve seen integral division by zero result
in a
SIGFPE), but generally:SIGSEGVoccurs when you access out ofbounds,
SIGBUSfor other accessing errors, andSIGILLfor an illegalinstruction. In this case, the most likely explination is that your
bounds error has overwritten the return address on the stack. If the
return address isn’t correctly aligned, you’ll probably get a
SIGBUS,and if it is, you’ll start executing whatever is there, which could
result in a
SIGILL. (But the possibility of executing random bytes ascode is what the standards committee had in mind when they defined
“undefined behavior”. Especially on machines with no memory
protection, where you could end up jumping directly into the OS.)