void getmemory(char *p)
{
p=(char *) malloc(100);
}
int main( )
{
char *str=NULL;
getmemory(str);
strcpy(p,"hello world");
printf("%s/n",str);
free(str);
return 0;
}
void getmemory(char **p)
{
*p=(char *) malloc(100);
}
int main( )
{
char *str = NULL;
getmemory(&str);
strcpy(str,"hello world");
printf("%s/n",str);
free(str);
return 0;
}
printf("%s/n",str);
->
printf("%s\n",str);
你的程序中的malloc函数申请的内存实在局部函数中进行的,当getmemory函数执行完返回时局部变量就会被系统回收,此时申请的内存又被回收了回去肯定不能返回了。另外,你在主函数中进行strcpy(p,"hello world")几个意思?!!太大意了吧。
因为当你的子函数getmemory调用完之后系统会释放你申请的空间,所以在当你在主函数中对str进行free时候很危险,毕竟你没有对str申请空间。