Why buffer overflow doesn't affect to this cod

2020-05-07 19:21发布

I have the following code:

int main(int argc, char *argv[])
{
    char ch[10];
    printf("String 10 max. :: "); gets( ch );

    printf("String: %s\n", ch);

    return 0;
}

When I run this with "12345678" as ch it runs well. The strange thing is when I run with "123456789012345678901234567890"! The second printf prints ALL the string (the 30 chars) to the screen.

Why does this happen? Why doesn't my code crash?

Thanks for your time,
Azteca

5条回答
来,给爷笑一个
2楼-- · 2020-05-07 19:44

You're not seeing any effect because you don't have any more local variables, change the code to this and you will

int main(int argc, char *argv[])
{
    char ch[10];
    int i=42;

    printf("String 10 max. :: "); gets( ch );

    printf("String: %s\n", ch);
    printf("i: %d\n", i);

    return 0;
}
查看更多
做自己的国王
3楼-- · 2020-05-07 19:48

A Buffer overflow only causes a "crash" (i.e., a segmentation fault), if you are trying to read/write from a page that has not been mapped. In that case, the memory management unit catches the error.

If you did not yet reach the end of the page, like in your example, the memory at that point is still valid from the operating system's/processor's point of view - you are just overwriting memory that might be used by another variable.

查看更多
虎瘦雄心在
4楼-- · 2020-05-07 19:48

The effect of a buffer overrun depends entirely what you overwrite, what you overwrite it with, and how the overwritten data is subsequently used.

The method of buffer overrun exploitation involves using the overrun to modify the return address of a function; but returning from main() to the OS may not be quite the same as returning from a function.

查看更多
够拽才男人
5楼-- · 2020-05-07 19:58

Buffer overflow is undefined behaviour. It may crash, but no one guarantee that. In most compilers, the stack grows down, so you probably override main's return address, but the call to printf doesn't override your string.

查看更多
\"骚年 ilove
6楼-- · 2020-05-07 20:03

By using memory that you are not supposed to use, you are entering the territory of undefined behavior. It doesn't crash today on your machine. But the behavior could change without warning.

For what it's worth, when I run the same code on my cygwin shell, I get

Segmentation fault (core dumped)
查看更多
登录 后发表回答