所有的自动变量以及函数调用时所需要保存的信息(返回地址、函数调用前各寄存器的值等)都存储在栈上。每次调用函数时,栈会随着函数的调用而生长,随着函数调用结束而消亡。
自动变量有3种存储方式:一是存储在数据段或者bss段(静态局部变量);一是存储在寄存器里(寄存器变量);一是存储在栈中(一般自动变量)。由于绝大多数自动变量存储在栈中,所以自动变量的作用域往往只在函数内,其生命周期也往往只持续到函数调用的结束。
注:C语言编程中,一种典型的错误就是将一个指向局部变量的指针作为函数的返回值返回。
示例:将一个指向局部变量的指针作为函数的返回值返回
local.c
#include <stdio.h>
#include <string.h>
char *combine(char *str1,char *str2)
{
char str[1024];
char *p=str;
strcpy(str,str1);
strcat(str,str2);
return p;
}
int main(void)
{
char *p;
p=combine("hello"," world");
printf("%s/n",p);
return 0;
}
[root@localhost yuan]# ./local
hello world
[root@localhost Untitled-1]# ./local
hello world
以及在VC++6.0下也可以正确运行
这些应该是个巧合~