Chinaunix首页 | 论坛 | 博客
  • 博客访问: 51024
  • 博文数量: 18
  • 博客积分: 1410
  • 博客等级: 上尉
  • 技术积分: 160
  • 用 户 组: 普通用户
  • 注册时间: 2008-01-31 19:48
文章分类
文章存档

2011年(1)

2010年(2)

2009年(15)

我的朋友

分类: C/C++

2010-02-23 11:10:59

按照一般教科书上的说法,C语言中的局部变量应该是分配在"栈"中的。而实际情况,有些出入,看看我下面的调试纪录,肯能更容易理解。

这是我写的一段代码,唯一的用途,就是分配变量。
int func1(void)
{
volatile int father;
volatile int mother;
volatile int boy;
volatile int girl;
father = 30;
mother = boy = girl = father;
return father;
}
int func2(void)
{
volatile int father;
volatile int mother;
volatile int boy;
volatile int girl;
volatile int unnecessary;
father = 30;
mother = boy = girl = father;
unnecessary = 0;
return father;
}
int func3(void)
{
volatile int stone[2];
stone[0] = 30;
return stone[0];
}
int func4(void)
{
volatile int stone[2];
stone[0] = 30;
if(stone[0] == 30)
{
volatile int father;
father = 91;
}
else
{
volatile int mother;
mother = 90;
}
return stone[0];
}
int func5(void)
{
volatile int stone[2];
stone[0] = 30;
if(stone[0] == 30)
{
volatile int boy[2];
boy[0] = 91;
}
else
{
volatile int girl[2];
girl[0] = 90;
}
return stone[0];
}
int func10(int a, int b, int c, int d)
{
return a + b + c + d;
}
int func11(int a, int b, int c, int d)
{
volatile int father = a;
volatile int mother = b;
volatile int boy = c;
volatile int girl = d;
return father + mother + boy + girl;
}
typedef struct Home
{
int father;
int mother;
} THome;
int func12()
{
THome home;
home.father= 12;
home.mother = 12;
return home.father + home.mother;
}
typedef int uint32;
int func13()
{
uint32 home = 2;
home *= 2;
return home;
}
int main(void)
{
func1();
func2();
func3();
func4();
func5();

func10(1,2,3,4);
func11(1,2,3,4);
func12();
func13();
}


通常,ADS编译的代码使用R13作为堆栈指针,也就是SP。

先看看刚进入main()函数的时候,R13=0x08000000。



单步执行一步后,R13=0x07FFFFC。减少了4字节,PC入栈引起。



进入fun1()后,R13=0x07FFFFC。没有变化,说明这几个变量没有入栈,实际上他们分别分配在R0-R3。



进入fun2()后,R13=0x07FFFF8。比0x07FFFFC少4字节,前4个仍然分配在R0-R3,第5个变量入栈。



进入fun3()后,R13=0x07FFFF0。比0x07FFFFC少12字节,除了数组入栈外,还有PC。



进入fun4()后,R13=0x07FFFF0。跟func4()一样,数组和PC入栈,分支中的变量放在R0中。



进入fun5()后,R13=0x07FFFE8。比fun4()少8字节,说明分支中的数组也入栈了。



进入fun10()后,R13=0x07FFFFC。4个函数形参也是分配在R0-R3。



进入fun11()后,R13=0x07FFFEC。比0x07FFFFC少16字节,4个形参仍然分配在R0-R3,另外4个变量入栈。



进入fun12()后,R13=0x07FFFF0。跟func4()一样,结构体变量也是入栈的。



进入fun13()后,R13=0x07FFFFC。没有变化,char、int这些变量即使经过typedef,其处理方法仍然不变。
阅读(600) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~