内存管理
来源:互联网 发布:被淘宝卖家骚扰怎么办 编辑:程序博客网 时间:2024/06/08 10:33
判断这段程序,它的问题有哪些?
#include <stdio.h>#include <string.h>#include <stdlib.h>void getmemory(char *p){p = (char *)malloc(100);}int main(void){char *str = NULL;getmemory(str);strcpy(str,"hello world!");printf("%s",str );}
这段程序执行之后会发生段错误,原因就是在调用函数getmemory时,传递的是指针str的形参,所以在函数调用结束后,str最终还是指向的NULL,并没有给str分配到实际的内存空间来让它存储数据。
如果将程序修改为下面这样,则能成功输出str的内容,打印"hello world!"语句。
#include <stdio.h>#include <string.h>#include <stdlib.h>void getmemory(char **p){*p = (char *)malloc(100);}int main(void){char *str = NULL;getmemory(&str);strcpy(str,"hello world!");printf("%s\n",str );}在调用函数getmemory时,传递str的地址给函数的参数,函数形参使用二级指针,则对*p分配内存空间时,就相当于对str指针分配了内存空间,使str指向了一段长度为100的char型空间。
- 内存管理
- 内存管理
- 内存管理
- 内存管理
- 内存管理
- 内存管理
- 内存管理
- 内存管理
- 内存管理
- 内存管理
- 内存管理
- 内存管理
- 内存管理
- 内存管理
- 内存管理
- 内存管理
- 内存管理
- 内存管理
- jquery菜单式图片轮播特效仿淘宝
- 内核宏ALIGN的含义
- python memcache安装与使用
- 隐马尔科夫模型
- 2.3 《硬啃设计模式》 第5章 “妞”太多,如何管理?(2)- 工厂方法(Factory Method Pattern)
- 内存管理
- linux下使用find xargs grep查找文件及文件内容
- [LeetCode] Balanced Binary Tree
- java项目视频
- window.onerror()的用法
- 教程网(要学费的)
- Linux rpm 命令参数使用详解[介绍和应用]
- java定时查询数据(1.struts1,2.sevlet)
- sqlite rename column name