面试的经典问题--函数中开空间

来源:互联网 发布:网络专科学历找工作 编辑:程序博客网 时间:2024/06/05 19:12

查看运行结果
1.

void GetMemory(char *p){    p = (char *) malloc(100);}int main(){  char *str = NULL:  GetMemory(str);  strcpy(str,"hello world");  printf("%s",str);}

运行结果:崩溃:p的地址没有带出来;

2.

char * GetMemory(){  char p[] = "hello world";  return p;}int main(){    char *str = NULL;    str = GetMemory();    printf(str);}

运行如果:随机的,乱码;p是一个局部变量,随着栈帧的回退,不存在

3.

void GetMemory(char **p,int num){    *p = (char*)malloc(num);}int main(){   char *str = NULL;   GetMemory(str,100);   strcpy(str,"hello world");   prinf(str);}

运行结果:正常运行,但是存在内存泄漏;

4.

void test(){     char *str = (char *)malloc(100);     strcpy(str,"hello world");     free(str);     if(str != NULL)     {     strcpy(str,"world");     peintf(str);     }}

运行结果:非常危险;可能直接崩溃;str是一个野指针;

原创粉丝点击