简体   繁体   English

c中for循环中的缓冲区数组溢出

[英]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? 分配的前50个字节会发生什么,程序什么时候会崩溃?

I see in my UBUNTU with gcc a.out it is crashing when i 99 我在UBUNTU中看到了gcc a.out,当我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? 我想知道为什么在for循环中在buff [51]上发生赋值时这不会崩溃?

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. 基本原理是c数组中没有编译或运行时'索引超出绑定检查 '。 That is present in STL vectors or arrays in other higher level languages. 这存在于STL向量或其他更高级语言的数组中。 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. 假设你在一个函数调用中,紧接着你的数组旁边是RETURN地址,即你的程序用来返回它调用的函数的地址。 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循环的代码中某处...至少这是它应该如何在理论上。

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

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