内存操作GetMemory
来源:互联网 发布:磁条卡读写软件 编辑:程序博客网 时间:2024/04/20 08:17
<span style="font-size:18px;">试题 4:void GetMemory( char *p ){p = (char *) malloc( 100 );}void Test( void ){char *str = NULL;GetMemory( str );strcpy( str, "hello world" );printf( str );} 试题 5:char *GetMemory( void ){char p[] = "hello world";return p;}void Test( void ){char *str = NULL;str = GetMemory();printf( str );} 试题 6:void GetMemory( char **p, int num ){*p = (char *) malloc( num );}void Test( void ){char *str = NULL;GetMemory( &str, 100 );strcpy( str, "hello" );printf( str );} 试题 7:void Test( void ){char *str = (char *) malloc( 100 );strcpy( str, "hello" );free( str );... //省略的其它语句}</span>
<span style="font-size:18px;"> 解答: 试题 4 传入中 GetMemory( char *p )函数的形参为字符串指针,在函数内部修改形参并不能真正的改变传入形参的值,执行完char *str = NULL;GetMemory( str ); 后的 str 仍然为 NULL; 试题 5 中char p[] = "hello world";return p; 的 p[]数组为函数内的局部自动变量,在函数返回后,内存已经被释放。这是许多程序员常犯的错误,其根源在于不理解变量的生存期。 试题 6 的 GetMemory 避免了试题 4 的问题,传入 GetMemory 的参数为字符串指针的指针,但是在 GetMemory 中执行申请内存及赋值语句*p = (char *) malloc( num ); 后未判断内存是否申请成功,应加上:if ( *p == NULL ){...//进行申请内存失败处理} 试题 7 存在与试题 6 同样的问题,在执行char *str = (char *) malloc(100); 后未进行内存是否申请成功的判断;另外,在 free(str)后未置 str 为空,导致可能变成一个“野”指针,应加上:str = NULL; 试题 6 的 Test 函数中也未对 malloc 的内存进行释放。 剖析: 试题 4~7 考查面试者对内存操作的理解程度,基本功扎实的面试者一般都能正确的回答其中 50~60 的错误。但是要完全解答正确,却也绝非易事。 对内存操作的考查主要集中在: (1)指针的理解; (2)变量的生存期及作用范围; (3)良好的动态内存申请和释放习惯。</span>
1 0
- 内存操作GetMemory
- Getmemory函数详解--内存操作的理解
- Getmemory函数详解--内存操作的理解
- 内存管理GetMemory
- 内存管理GetMemory
- 关于内存 GetMemory
- 有关内存的思考?GetMemory()
- GetMemory
- GetMemory
- GetMemory()
- GetMemory
- GetMemory()
- GetMemory
- 有关内存的GetMemory()函数
- 牛客 题库 4 内存管理GetMemory
- Getmemory的几个经典的关于内存的笔试题
- 从GetMemory()看C/C++内存分配机制
- C++常见面试题—内存管理GetMemory()
- 自定义ProgressBar(使用图片播放效果)
- 【已解决】Eclipse for Android 出现Could not find SDK folder....问题解决
- cordys 的 ESB如果实现数据转换
- ostringstream的简单用法(用于一次文件内容全部读入)
- windows7安装oracle 10g安装过程及注意事项
- 内存操作GetMemory
- 创建型模式之工厂方法模式(日志记录器)
- ubifs烧写到nand flash中的几种方法
- Android动画学习笔记
- ccflow 删除附件bug&审核时节点字段数据丢失bug&递归查找签核人bug
- Linux内核源代码情景分析笔记---对照4.2.5内核 续
- MyBatis 缓存机制深度解剖 / 自定义二级缓存
- ZooKeeper-3.3.4集群安装配置
- solr乱七八糟总结,真的很乱