代码如下:
#include
#include
#include
// function prototype declaration
int heap_overflow(unsigned int n, char c);
void func1(void);
void func2(void);
void func3(void);
void func4(void);
void func5(void);
// 注意:每个函数需要单独执行测试,因此在测试每个函数时,需要将其他函数屏蔽。
int main(void)
{
// 堆溢出访问演示
//heap_overflow(9, *t*); // The 9th element = t.
//heap_overflow(99, *g*); // The 99th element = g.
heap_overflow(9999999, *g*); // Segmentation fault
// 栈溢出访问演示
//func1(); // stack smashing detected
//func2(); // factorial(10) = 3628800.
//func3(); // Segmentation fault
//func4(); // a[1048576-1] = 5.
//func5(); // Segmentation fault
return 0;
}
int heap_overflow(unsigned int n, char c)
{
char *p = NULL;
p = (char *)malloc(16);
if (NULL == p)
{
printf("fail to get dynamic memory from heap.\n");
return -1;
}
memset(p, 0, 16);
*(p + n) = c;
printf("The %dth element = %c.\n", n, *(p + n));
free(p);
p = NULL;
return 0;
}
void func1(void)
{
char name[8];
strcpy(name, "linus tovards.");
printf("Hello, %s!", name);
}
static unsigned int factorial(unsigned int n)
{
if (n == 1)
return 1;
else
return n * factorial(n - 1);
}
void func2(void)
{
printf("factorial(10) = %d.\n", factorial(10));
}
void func3(void)
{
printf("factorial(10000000) = %d.\n", factorial(10000000));
}
#define M (1 * 1024 * 1024)
#define N (4 * 1024 * 1024)
void func4(void)
{
int a[M];
a[M-1] = 5;
printf("a[%d-1] = %d.\n", M, a[M-1]);
}
void func5(void)
{
int a[N];
a[N-1] = 5;
printf("a[%d-1] = %d.\n", N, a[N-1]);
}