简体   繁体   English

为什么缓冲区溢出不会影响此代码?

[英]Why buffer overflow doesn't affect to this code?

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. 当我使用"12345678"作为ch运行它时,它运行良好。 The strange thing is when I run with "123456789012345678901234567890" ! 奇怪的是,当我运行"123456789012345678901234567890" The second printf prints ALL the string (the 30 chars) to the screen. 第二个printf所有字符串(30个字符)打印到屏幕上。

Why does this happen? 为什么会这样? Why doesn't my code crash? 为什么我的代码没有崩溃?

Thanks for your time, 谢谢你的时间,
Azteca 阿兹台克

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. 在大多数编译器中,堆栈会变小,因此您可能会覆盖main的返回地址,但对printf的调用不会覆盖您的字符串。

A Buffer overflow only causes a "crash" (ie, 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. 如果您尚未到达页面末尾(例如您的示例),则从操作系统/处理器的角度看,该点的内存仍然有效-您只是在覆盖可能由另一个变量使用的内存。

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;
}

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 值得的是,当我在cygwin shell上运行相同的代码时,

Segmentation fault (core dumped)

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. 但是从main()返回到OS可能与从函数返回不完全相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM