若将用户定义的函数中的值通过指针返回给main函数会存在一定风险。
#include<stdio.h>
int *f1(void);
void f2();
int main(int atgc, char const* argv[])
{
int* p= f1();
printf("%d\n", *p);
f2();
printf("%d\n", *p);
return 0;
}
int *f1(void)
{
int a = 100;
return &a;
}
void f2(void)
{
int b = 200;
}
其输出结果为:
由此得出返回指针时其地址会在之后被其他函数的变量所占用,存在风险。
但是返回全局变量或静态本地变量的地址时安全的;
返回在函数内的malloc的内存也是安全的,但容易造成问题;
最好的做法应该是返回传入的指针。