这道华为面试题有什么问题?
void getmemory(char *p){ p=(char *)malloc(100); strcpy(p,"hello world");}int main(int argc, char* argv[]){ char *str=NULL;//"ni hao"; getmemory(str); printf("%s\n",str); free(str); return 0;}#include <stdio.h>#include <stdlib.h>#include <string.h>void getmemory(char **p){ *p=(char *)malloc ( 100 ); strcpy ( *p, "hello world" );}int main(int argc, char* argv[]){ char *str = NULL;//"ni hao"; getmemory ( &str ); printf ( "%s\n", str ); free ( str ); return 0;}
[解决办法]
在调用 getmemory 的时候传入的是 char *, 仅仅是 str 的一个副本, getmemory 函数里的语句不会修改str的值, 而是它的副本的值, 在函数结束时 *p 被释放, 发生了内存泄漏。
而在 printf 的时候由于 str 是空指针, 不会输出, 然后对一个空指针 free 就segment fault 了
[解决办法]
+1
在getmemory 中分配的内存中无法传出来,所以Free一个空指针,这个操作时未定义的,崩不崩溃看运气了
#include <stdio.h>#include <stdlib.h>#include <string.h>char *getmemory ( void ){ char *p; p = (char *)malloc ( 100 ); strcpy ( p, "hello world" ); return p;}int main(int argc, char* argv[]){ char *str = NULL;//"ni hao"; str = getmemory (); printf ( "%s\n", str ); free ( str ); return 0;}
[解决办法]
up
用双指针或者函数返回指针#include <stdio.h>void getmemory(char *p){ p=(char *)malloc(100); printf("p=%p\n",p); //形参p指向的地址 strcpy(p,"hello world");}int main(int argc, char* argv[]){ char *str=NULL;//"ni hao"; printf("str=%p\n",str); //实参str指向的地址 getmemory(str); printf("str=%p\n",str); //调用函数后str指向的地址 ,str指向的地址没有被改变,它没有指向函数内所开辟的空间 printf("%s\n",str); free(str); system("pause"); return 0;}
[解决办法]
至于free,对于空指针无论怎么free都是没问题的!