堆栈溢出的示例代码

时间:2011-03-14 08:20:09

标签: linux

您好 你能给我一个c或.net堆栈溢出的示例代码吗?并告诉我你如何解决这个错误。

谢谢

4 个答案:

答案 0 :(得分:1)

怎么样:

static void f(void) {
    f();
}
int main (void) {
    f();
    return 0;
}

这应该会给你一个非常好的堆栈溢出,解决方案是:不要那样做。

答案 1 :(得分:1)

#include <string.h>

void function( char *str ) {
   char buf[8];

   strcpy(buffer,str);
}

void main( int argc, char *argv[] ) {
  function( argv[1] );
}

经典例子。 strcpy()复制而不检查任何大小。因此,如果源字符串(str)大于缓冲区(buf),则会出现缓冲区溢出。让它说16chars你会得到堆栈溢出。

您可以使用更安全的功能,例如strncpy来解决此错误。

答案 2 :(得分:0)

你的意思是说用完了堆栈空间,还是做了恶意的事情?

关于恶意溢出堆栈的经典文章:

http://insecure.org/stf/smashstack.html

如果你的意思是刚用完堆栈空间,你需要做的就是有一个递归函数,最终会在堆栈上分配太多空间,并且用完了:

int foo()
{
    int something = 4;
    foo();
    return something; /* Yeah, we never get here */
}

答案 3 :(得分:0)

int factorial(int x)
{
    if (x == 1 || x == 0) return 1;
    return factorial(x-1) * x;
}

factorial(-1);

确保递归函数总是以某种方式达到基本情况。

int factorial(int x)
{
    if (x < 0) return 0;
    if (x == 1 || x == 0) return 1;
    return factorial(x-1) *x;
}

factorial(-1);
相关问题