|
突然想到一个作用域和生命周期的问题,于是就编了一个程序检验一下
[php]#include <stdio.h>
char *beyond_boundary();
int main()
{
char *p=beyond_boundary();
printf("Return value is: %s\n",p);
printf("%X\n",p);
}
char * beyond_boundary()
{
char *p="auto string";
printf("%X\n",p);
return p;
}[/php]
我的设想是这样的,函数中的自动变量应该在栈上分配空间,beyond_boundary()函数中的字符串空间应该在函数调用后就不存在了,printf("Return value is: %s\n",p);这句应该会有segmentary fault才对啊
可是我编译运行时却能正确显示auto string这个字符串
- [leo@leo test]$ ./a.out
- 8048511
- Return value is: auto string
- 8048511
- [leo@leo test]$ echo $?
- 8
复制代码 但返回值非零
我又用gdb跟踪了一下,好像是有点问题,但我看不懂
希望哪位大虾不吝赐教
thx |
|