【面试题】关于GetMemory的故事

来源:互联网 发布:php use继承 编辑:程序博客网 时间:2024/04/29 19:38
#include <iostream>using namespace std;void GetMemory(char *p, int num){p = (char *)malloc(sizeof(char) * num);}void main(){char *str = NULL;GetMemory(str,100);strcpy(str,"Hello");}//编译通过,但运行错误。//0x61aef689 (msvcr90d.dll) 处未处理的异常: 0xC0000005: 写入位置 0x00000000 时发生访问冲突


p实际是str的一个副本,编译器总是要给函数的每个参数制作临时副本。p动态申请了内存,只是把p所指向的内存地址改变了,str没有改变。函数GetMemory运行完后,str还是NULL,所以运行报错,内存读取错误。。。

 

#include <iostream>using namespace std;void GetMemory(char **p, int num){*p = (char *)malloc(sizeof(char) * num);}void main(){char *str = NULL;GetMemory(&str,100);strcpy(str,"Hello");printf("%s",str);}//传入str的地址。指针的地址。这样就可以影响到str了。//编译通过,运行输出Hello。


#include <iostream>using namespace std;char *GetMemory(char *p, int num){p = (char *)malloc(sizeof(char) * num);return p;}void main(){char *str = NULL;str = GetMemory(str,100);strcpy(str,"Hello");printf("%s",str);}//返回申请的空间给str,这样也可以。//编译通过,运行输出Hello。

 

#include <iostream>using namespace std;char *GetString(){char str[] = "Hello\n";return str;}void main(){char *str = NULL;str = GetString();printf("%s",str);}//编译通过,运行输出乱码。//因为GetString中的str数组是局部数组,存在于栈中。//函数调用完,会栈空间收回。



#include <iostream>using namespace std;char *GetString(){char *str = "Hello\n";return str;}void main(){char *str = NULL;str = GetString();printf("%s",str);}//编译通过,运行输出Hello。//因为GetString中的str是字符串常量,常量区中。


 

原创粉丝点击