题目
#include<stdio.h>
char * GetMemory(void)
{
char p[] = "hello world";
return p;
}
int main()
{
char * str;
str = GetMemory();
printf("%s",str);
return 0;
}
Question: Is the code above correct? if not correct, please modify it.
成因:栈销毁时栈上的地址也就没用意义了,返回值是个野指针
解决办法1:这也是原帖中的解决办法,在char p前加static,使其成为静态变量,这样栈消亡时p的地址依然有意义。
解决办法2:使用二级指针,代码如下
#include<stdio.h>
void GetMemory(char **p)
{
*p = "hello world";
return;
}
int main()
{
char * str;
GetMemory(&str);
printf("%s",str);
return 0;
}