0

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';
user2455103
  • 505
  • 2
  • 4
  • 13
  • 3
    That doesn't overflow the stack, that writes past the end of an array. Obviously you didn't study very hard... BTW, change the loop size to 4100 and you're far more likely, though still not guaranteed, to get a crash or something – Mooing Duck Jul 19 '13 at 22:16
  • Yeah sorry i didn't read you answer conpletely. However, in many tutorials , they use such code in order to edit the ret addresses of functions – user2455103 Jul 19 '13 at 22:18
  • It's not a stack overflow it's a buffer overflow. – syam Jul 19 '13 at 22:20
  • Yeah buffer overflow, sorry – user2455103 Jul 19 '13 at 22:20
  • Sorry for not throughly searching before asking..... I consider the question closed. Thanks – user2455103 Jul 19 '13 at 22:30
  • possible duplicate of [Array overflow (why does this work?)](http://stackoverflow.com/questions/10051782/array-overflow-why-does-this-work) – Mooing Duck Jul 19 '13 at 23:10

2 Answers2

2

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.

Joel
  • 1,135
  • 6
  • 9
1

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

Community
  • 1
  • 1
TooTone
  • 7,129
  • 5
  • 34
  • 60