Martin Cox
Martin Cox

Reputation: 95

Not getting a segmentation fault when expecting it

I'm toying with buffer overflows, but I'm confused by what I'm finding when running the following simple C program on Mac OS.

#include <stdio.h>

int main(void) {

        char buf[2];

        scanf("%s", buf);

        printf("%s\n", buf);

}

By setting the length of buf to 2 bytes, I expected to cause a segmentation fault when entering the string "CCC", but that doesn't happen. Only when entering a string 24 characters in length do I incur a segmentation fault.

What's going on? Is it something to do with character encoding?

Thanks.

Upvotes: 2

Views: 248

Answers (5)

ChrisWue
ChrisWue

Reputation: 19020

Because buf is on the stack. When you start overwriting it, you start overwriting the stack which belongs to the program which the OS won't catch depending on what else is allocated there (e.g. spill slots for registers created by the compiler). Only once you cross the allocated stack boundary the OS will have a chance to raise a segfault.

Upvotes: 2

Karoly Horvath
Karoly Horvath

Reputation: 96266

buf is allocated on the stack, you're just overwriting an area that's not used there is a good chance that nobody will complain about it. On some platforms your code will accept whole paragraphs.

Upvotes: 1

Piotr Praszmo
Piotr Praszmo

Reputation: 18320

There is no guarantee that you will get segmentation fault at all. There is more data after char buf[2] overwriting it may or may not cause segmentation fault.

Upvotes: 1

Mat
Mat

Reputation: 206727

The behavior of your program is undefined as soon as you overflow the buffer. Anything can happen. You can't predict it.

There might or might not be some padding bytes after your buffer that happen to be unimportant to your code execution. You can't rely on that. A different compiler, compiling in 32bit vs 64bit, debug settings... all that could alter your code execution after that overflow.

Upvotes: 5

cnicutar
cnicutar

Reputation: 182649

I guess it's related to the memory layout. If what you are overwriting is accessible to your process (a page mapped writable) the OS doesn't have a chance to see you're doing something "wrong".

Indeed, when doing something like this, from the eyes of a C programmer "that's totally wrong!". But in the eyes of the OS "Okay, he's writing stuff to some page. Is the page mapped with the adequate permissions ? If it is, OKAY".

Upvotes: 1

Related Questions