每日一题(20)——malloc与free(一)
来源:互联网 发布:网络日报 编辑:程序博客网 时间:2024/06/01 12:48
void GetMemory(char *p){ p = (char *)malloc(100);} void Test(void){ char *str = NULL; GetMemory(str); strcpy(str, "hello world"); printf(str);}
1、指出编程错误
2、指出错误后果
3、指出纠正方法
分析:
1、调用GetMemory( str )后, str并未产生变化,依然是NULL.只是改变的str的一个拷贝的内存的变化
2、strcpy( str, "hello world" );程序运行到这将产生错误。
3、推荐使用2级指针形式,如下:
void GetMemory(char **p, int num){ *p = (char *)malloc(sizeof(char) * num);}void Test(void){ char *str=NULL; GetMemory(&str, 100); strcpy(str,"hello world"); printf(str); free(str); str=NULL;}
阅读全文
0 0
- 每日一题(20)——malloc与free(一)
- 每日一题(21)——malloc与free(二)
- 每日一题(22)——malloc与free(三)
- 每日一题(23)——malloc与free(四)
- glibc2.5 中的malloc 与 free 之我见(一)
- 一,malloc free 函数
- 每日一题(10)—— 数组与指针
- malloc与free(1)
- malloc与free(2)
- malloc与free(3)
- 每日一题(一)
- 田蕴章书法讲座《每日一题,每日一字》(3) 文字整理 ——左右二字与毛笔
- 每日一linux命令(36)-------free 命令
- 面试—每日一题(1)
- 面试—每日一题(2)
- 面试—每日一题(3)
- 面试—每日一题(4)
- 面试—每日一题(5)
- [算法与数据结构]
- java面试题,各大企业常见的java笔试题之七
- 概率与期望
- 坚持写博客
- 《深入理解Java虚拟机》读后总结之JVM垃圾回收
- 每日一题(20)——malloc与free(一)
- 菜鸟心历之路(10)
- nrf52832 gpio9和10默认是NFC,非普通GPIO
- StreamTook(周考1)
- Xutils
- 在web应用中使用solr(一)
- 搭建自己的Linux根文件系统
- 重写Python脚本时关于建立框架的想法
- LightOJ 1070 Algebraic Problem