Question

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)

The same happens if i swap:

cin>>input[i];

with :

input[i]='a';
Était-ce utile?

La solution

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.

Autres conseils

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

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.

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...

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top