堆栈溢出的示例代码
如何:
static void f(void) {
f();
}
int main (void) {
f();
return 0;
}
这应该给你一个很好的堆栈溢出,解决是:不这样做。
你的意思是用完堆栈空间,或者做些恶意的事情?
上恶意溢出堆栈中的经典文章:
http://insecure.org/stf/smashstack.html
如果你的意思是跑出来的堆栈空间,所有你需要做的是在结束了对分配太多空间递归函数堆栈,并运行了:
int foo()
{
int something = 4;
foo();
return something; /* Yeah, we never get here */
}
从技术上讲,这是一个缓冲区溢出而不是堆栈溢出,但它仍然是一个非常好的文章。 – paxdiablo 2011-03-14 08:25:11
我不认为他意味着缓冲区溢出,但感谢张贴该文章!我没有看到它之前 – 2011-03-14 08:25:59
他说栈...我刚刚编辑了一个递归函数,最终会用完。 – 2011-03-14 08:27:25
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);
这不会永久递归。 – 2011-03-14 08:24:54
哦,很好,@Ignacio。 jon_d,你应该使用'=='而不是'=':-) – paxdiablo 2011-03-14 08:27:06
哈哈感谢良好的调用 – 2011-03-14 08:27:28
#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这样更安全的函数来解决此错误。
分辨率很简单。只是不要做任何样本。 – 2011-03-14 08:22:17