0

Hello Can you give me a sample code for overflow in stack with c or .net ? and say me how do you resolve this bug.

Thank you

1
  • 2
    The resolution is easy. Just don't do whatever the sample does. Commented Mar 14, 2011 at 8:22

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0
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);

4 Comments

This will not recurse forever.
Ooh, good catch, @Ignacio. jon_d, you should use == rather than = :-)
Actually, it may not overflow anyway if tail end recursion optimisation happens. But, then again, my answer could have the call to f() optimised out of existence since it does nothing :-)
figured id make it non-trivial while i was at it
0

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 */
}

3 Comments

Technically, that's a buffer overflow rather than a stack overflow, but it's a damn good article nonetheless.
i dont think he means buffer overflow, but thanks for posting that article! i hadnt seen it before
He said stack ... I just edited with a recursive func that will eventually run out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.