简体   繁体   中英

Buffer array overflow in for loop in c

When would a program crash in a buffer overrun case

#include<stdio.h>
#include<stdlib.h>

main() {
    char buff[50];
    int i=0;
    for( i=0; i <100; i++ )
    {
        buff[i] = i;
        printf("buff[%d]=%d\n",i,buff[i]);
    }
}

What will happen to first 50 bytes assigned, when would the program crash?

I see in my UBUNTU with gcc a.out it is crashing when i 99

>>
buff[99]=99
*** stack smashing detected ***: ./a.out terminated
Aborted (core dumped)
<<

I would like to know why this is not crashing when assignment happening at buff[51] in the for loop?

It is undefined behavior . You can never predict when (or if at all ) it crashes, but you cannot rely upon it ' not crashing ' and code an application.

Reasoning

The rationale is that there is no compile or run time 'index out of bound checking ' in c arrays. That is present in STL vectors or arrays in other higher level languages. So whenever your program accesses memory beyond the allocated range , it depends whether it simply corrupts another field on your program's stack or affects memory of another program or something else, so one can never predict a crash which only occurs in extreme cases . It only crashes in a state that forces the OS to intervene OR when it no longer remains possible for your program to function correctly.

Example

Say you were inside a function call, and immediately next to your array was, the RETURN address ie the address your program uses to return to the function it was called from. Suppose you corrupted that and now your program tries to return to the corrupted value, which is not a valid address. Hence it would crash in such a situation.

The worst happens when you silently modified another field's value and didn't even discover what was wrong assuming no crash occurred.

因为看起来你已经在堆栈上分配了缓冲区,所以应用程序可能会在第一次覆盖要执行的指令时崩溃,可能在for循环的代码中某处...至少这是它应该如何在理论上。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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