Why buffer overflow doesn't affect to this code?

安稳与你 提交于 2019-12-02 21:48:09

问题


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


回答1:


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



回答2:


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.




回答3:


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:


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)



回答5:


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.



来源:https://stackoverflow.com/questions/23226217/why-buffer-overflow-doesnt-affect-to-this-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!