栈溢出
这里为了比较容易的展示栈溢出的问题,在main函数利用递归方法计算阶乘,代码如下:
#include <stdio.h>
#include "main.h"
static uint32_t spSatte[200];
static uint32_t spIndex = 0;
/*为什么要用浮点数,因为数据非常大整型很快就会溢出*/
float factorial(uint32_t n)
{
uint32_t sp = __get_MSP();
/*记录栈指针的变化情况*/
spSatte[spIndex++] = sp;
if(n==0 || n==1)
return 1;
else
return (float)n*factorial(n-1);
}
int main(void)
{
float x = 0;
uint32_t n = 20;
printf("stack test:\n");
x = factorial(n);
/*打印栈指针变化情况*/
for(int i = 0;i<spIndex;i++)
printf("MSP->%08X\n",spSatte);
/*打印阶乘结果*/
printf("factorial(%d)=%f\n",n,x);
while (1)
{
}
}
为方便观察,将stm32f407xx_flash.icf 将栈改为256字节
/*stm32f407xx_flash.icf 将栈改为256字节*/
define symbol __ICFEDIT_size_cstack__ = 0x200;
define symbol __ICFEDIT_size_heap__ = 0x200;
全编译后通过map文件来看下栈/堆的分配情况:
"P2", part 3 of 3: 0x400
CSTACK 0x2000'05d8 0x200 <Block>
CSTACK uninit 0x2000'05d8 0x200 <Block tail>
HEAP 0x2000'07d8 0x200 <Block>
HEAP uninit 0x2000'07d8 0x200 <Block tail>
- 0x2000'09d8 0x400
直观些,翻译成下图,CSTACK段分配在0x2000 05D8-0x2000 07D8,堆分配在0x2000 07D8-0x2000 09D8。
|