Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I not getting a segmentation fault with this code? (Bus error)

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)

like image 273
owagh Avatar asked Dec 22 '22 01:12

owagh


2 Answers

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: SIGSEGV occurs when you access out of bounds, SIGBUS for other accessing errors, and SIGILL for an illegal instruction. 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 as code 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.)

like image 153
James Kanze Avatar answered Dec 24 '22 02:12

James Kanze


A segmentation fault is never guaranteed when you're doing fishy stuff with memory. It all depends on a lot of factors (how the compiler lays out the program in memory, optimizations etc).

What may be illegal for a C++ program may not be illegal for a program in general. For instance the OS doesn't care if you step outside an array. It doesn't even know what an array is. However it does care if you touch memory that doesn't belong to you.

like image 30
cnicutar Avatar answered Dec 24 '22 03:12

cnicutar