刚随手打印地址过程中,看到了相同的两个地址
#include <stdio.h>
void fun1(){
int a1;
printf("&a1: %p\n", &a1);
}
void fun2(){
int a2;
printf("&a2: %p\n", &a2);
}
void main(){
fun1();
fun2();
}
lihui@2015 ~$ cc 1.c
lihui@2015 ~$ ./a.exe
&a1: 0x22aaac
&a2: 0x22aaac
而这连个函数调用是串行的,也就是这段内存地址重复使用了,也就是fun1执行完了之后,a1的那块内存区域释放掉了,执行到fun2,再次来使用
进一步多打印一些变量地址
#include <stdio.h>
void fun(int a, int b){
int c, d;
printf("fun &a: %p\n", &a);
printf("fun &b: %p\n", &b);
printf("fun &c: %p\n", &c);
printf("fun &d: %p\n", &d);
}
void main(){
int a, b;
printf("main &a: %p\n", &a);
printf("main &b: %p\n", &b);
fun(1, 2);
}
lihui@2015 ~
$ ./a.exe
main &a: 0x22aadc
main &b: 0x22aad8
fun &a: 0x22aab0
fun &b: 0x22aab8
fun &c: 0x22aa9c
fun &d: 0x22aa98
变量和地址的顺序关系图如下
0x22aa98 4bytes fun &d 0x22aa9c 4bytes fun &c ........ Nbytes 0x22aab0 4bytes fun &a 0x22aab4 4bytes 0x22aab8 4bytes fun &b ........ Nbytes 0x22aad8 4bytes main &b 0x22aadc 4bytes main &a
可见main函数的局部变量,fun的局部变量和形参相比,fun相关的几个变量地址更小;也就是分配内存区间的时候,都是以堆积在已经被分配的内存区域上面的方式,就跟数据结构里的栈一样,新来的放在栈顶;当函数返回结束的时候,相关变量内存会释放,相当于又出栈了,所以假如又来个串行的函数申请内存,又重新使用了刚才释放的内存区域,所以才有了地址想同的情况
局部变量分配在栈里,内存区域可以重复利用,对于函数调用
