【面试题】关于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是字符串常量,常量区中。
- 【面试题】关于GetMemory的故事
- GetMemory面试题
- 面试题Getmemory
- getmemory面试题
- GetMemory函数详解 (360面试题)
- C/C++ 笔试面试(3)——内存管理GetMemory 确实遇到的面试题
- js面试题Foo.getName()的故事
- 关于void GetMemory(*p)与void* GetMemory()的讨论
- C语言面试题之——getmemory
- C++常见面试题—内存管理GetMemory()
- C++常见面试题—内存管理GetMemory()
- 关于Servlet的面试题
- 关于Tencent的面试题
- 关于Servlet的面试题
- 关于概率的面试题
- 面试题 关于JAVA 的
- 关于数组的面试题
- 关于Servlet的面试题
- 【面试题】sizeof 获取自定义类,结构体,vector,map,string的占内存大小
- HDU 2132 An easy problem 小技巧
- poj 2923 Relocation 二进制状态压缩 深搜+广搜
- 用ASP.NET制作个人信息维护页面 使用 Label 、 TextBox 、 Button 制作个人信息维护页面
- hdu 2115 I Love This Game 典型的结构体排序
- 【面试题】关于GetMemory的故事
- js排序输出
- hdu 2114 Calculate S(n) 简单数学题
- Linux编程之路
- 求素数,回文数,回文素数,可逆素数
- 筛法求素数
- 多选对话框取值问题
- istringstream
- hdu 2133 日期的格式转化