sample code for overflow in stack
Hello Can you give me 开发者_JS百科a sample code for overflow in stack with c or .net ? and say me how do you resolve this bug.
Thank you
How about:
static void f(void) {
f();
}
int main (void) {
f();
return 0;
}
That should give you a very nice stack overflow, the solution to which is: don't do that.
#include <string.h>
void function( char *str ) {
char buf[8];
strcpy(buffer,str);
}
void main( int argc, char *argv[] ) {
function( argv[1] );
}
Classic example. strcpy() copies without checking any sizes. So, if your source string (str) is bigger than the buffer (buf) you will get a buffer overflow. Making it say 16chars you will get a stack overflow.
You can resolve this bug by using a safer function like strncpy.
int factorial(int x)
{
if (x == 1 || x == 0) return 1;
return factorial(x-1) * x;
}
factorial(-1);
Make sure recursive functions always reach a base case somehow.
int factorial(int x)
{
if (x < 0) return 0;
if (x == 1 || x == 0) return 1;
return factorial(x-1) *x;
}
factorial(-1);
Do you mean running out of stack space, or doing something malicious?
The classic article on overflowing the stack maliciously:
http://insecure.org/stf/smashstack.html
If you mean just running out of stack space, all you need to do is have a recursive function that ends up allocating too much space on the stack, and running out:
int foo()
{
int something = 4;
foo();
return something; /* Yeah, we never get here */
}
精彩评论