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
You're not seeing any effect because you don't have any more local variables, change the code to this and you will
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.
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.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 toprintf
doesn't override your string.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