面试题一:我该怎么回答你
#include <stdio.h>#include <stdlib.h>void getmemory(char *p){p=(char *) malloc(100);strcpy(p,"hello world");}int main( ){char *str=NULL;getmemory(str);printf("%s/n",str);free(str);return 0;}这是一段偶然看到的代码,然后看到一段评论是“程序崩溃,getmemory中的malloc不能返回动态内存,free()对str操作很危险。”我猜这个意思是没错的,说的是分配和释放存储不规范。
?
值得怀疑的是这段代码到底有多危险,我们知道C函数调用参数是值传递,那么str的值调用在getmemory结束后仍然是NULL。所以程序崩溃倒不会,让人崩溃的是子函数中分配的内存无从释放。
?
尽管下面的代码的确能工作,不过还是不要在你的程序里出现咯~
#include <stdio.h>#include <stdlib.h>void getmemory(char **p){*p=(char *) malloc(100);strcpy(*p,"hello world");}int main( ){char *str=NULL;getmemory(&str);printf("%s/n",str);free(str);return 0;}?