问题是非常明显的,所以我只会告诉你一些代码:)有什么办法可以避免静态内存区溢出?
#include <stdio.h>
#include <string.h>
char *test1()
{
static char c;
char *p;
p = &c;
printf("p[%08x] : %s\n", (unsigned int)p, p);
return p;
}
void *test2()
{
static char i;
char *buf;
int counter = 0;
for(buf = (char *)&i ; ;counter += 8)
{
memset(buf + counter, 0xff, 8);
printf("write %d bytes to static area!\n", counter);
}
}
int main()
{
char *p;
p = test1();
strcpy(p, "lol i asd");
p = test1();
strcpy(p, "sunus again!");
p = test1();
strcpy(p, "sunus again! i am hacking this!!asdfffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
p = test1();
test2();
return 0;
}
首先我写了test1()
。 正如你所看到的,那些strcpy
s应该会导致段错误,因为它显然访问非法的内存区域。我知道一些关于静态变量的基本知识,但这对我来说很奇怪。
然后我写了test2()
。 最后,它引起了段错误,之后它写了将近4k字节。
所以,我不知道如何避免这种错误(静态变量溢出)发生?
为什么我可以访问这些静态内存区域? 我知道他们不在堆栈中,也没有堆积。
PS。也许我没有清楚地描述我的问题。我有几年的C编程经验;我知道如果这不是静态的,会发生什么。 现在静态变化几乎所有,我想知道为什么。
如果您使用Shift键,您的问题会更容易阅读。 – 2012-03-12 04:44:36
@Eric J .:或者至少学会正确使用它。 – BoltClock 2012-03-12 04:45:25