python堆栈溢出的原因_堆栈溢出一般是什么原因导致的?

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼

代码如下:

#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]);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值