在以下示例中,函数
那么,这是良好定义的行为吗?
func()
返回一个指向本地指针变量的地址给main()
函数。在GCC中运行良好。那么,这是良好定义的行为吗?
#include <stdio.h>
#include <stdlib.h>
int *func(void);
int *func(void)
{
int *p;
p = malloc(sizeof *p);
*p = 10;
return p;
}
int main()
{
int *ptr = func();
printf("%d\n",*ptr);
return 0;
}
func
函数中,指针的地址应该是&p
,在main
函数中则应该是&ptr
。当然,一个指针的值就是一个地址(但它指向的是对象的地址)。 - user2371524