简体   繁体   English

数组缓冲区溢出

[英]Array buffer overflow

I have been studying about buffer 我一直在研究缓冲

#include <iostream>

using namespace std;

int main()
  {
 char input[3];
 for(int i=0;i<100;i++){
    cin>>input[i];
  }
return 0;
}

The program goes on and on without stopping and with no signs of an overflow (tested in 2 linux boxes) 程序不断运行,没有停止并且没有溢出迹象(在2个Linux盒子中进行了测试)

The same happens if i swap: 如果我交换,也会发生相同的情况:

cin>>input[i];

with : 与:

input[i]='a';

That's a buffer overflow, not a stack overflow. 那是缓冲区溢出,而不是堆栈溢出。 That code will trash the stack, but you might see an access violation crash if you're lucky. 该代码将破坏堆栈,但是如果幸运的话,您可能会看到访问冲突崩溃。 It won't trigger a stack overflow, which will only occur if you call too many functions - usually through recursion. 它不会触发堆栈溢出,只有在您调用太多函数(通常是通过递归)时才会发生。

void f()
{
    f(); // <-- stack overflow sure to happen
}

If you're looking for something to happen, there is no guarantee that it will. 如果您正在寻找可能发生的事情,则不能保证一定会发生。 Writing past the end of an array is undefined behavior. 超出数组末尾的写入是未定义的行为。 If the system detects what you're doing it will almost certainly crash you, but if you're just overwriting memory that actually does belong to your process it might not happen until you write way past the end. 如果系统检测到您正在执行的操作,几乎肯定会使您崩溃,但是如果您只是覆盖实际上确实属于您的进程的内存,则可能要等到您写完结尾之后,才会发生。

see What and where are the stack and heap? 请参阅堆栈和堆在哪里?

You'll get a stack overflow pretty quickly if you produce a function that calls itself endlessly. 如果产生一个不断调用自身的函数,则很快就会导致堆栈溢出。 Each function call will take up space on the stack, and you will run out of stack space very quickly! 每个函数调用都会占用堆栈空间,并且您很快就会用完堆栈空间!

void f()
{
    f();
}

In Visual Studio 2012, this code even produced a warning 在Visual Studio 2012中,此代码甚至产生警告

warning C4717: 'f' : recursive on all control paths, function will cause runtime stack overflow

The function didn't get optimized out on Visual Studio 2012, but nevertheless, as @MooingDuck points out, compilers can be rather clever at spotting optimizations and potential errors in code. 该功能尚未在Visual Studio 2012上进行优化,但是正如@MooingDuck指出的那样,编译器可以非常聪明地发现优化和代码中的潜在错误。

Tell-tale sign of a stack overflow is seeing the same function repeated over and over in your call stack in your program when your program crashes! 当程序崩溃时,堆栈溢出的迹象表明在程序的调用堆栈中反复看到相同的函数! Probably better to see how it looks now so you now how to recognize it in future... 大概更好地了解它的外观,以便您现在如何在将来识别它...

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

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