C++中有关内存的思考
来源:互联网 发布:剪辑声音的软件 编辑:程序博客网 时间:2024/06/05 11:25
1
#include <iostream>
using namespace std;
void GetMemory(char *p)
{
p=(char *)malloc(100);
}
void Test(void)
{
char *str=NULL;
GetMemory(str);
strcpy(str,"Hello world");
printf(str);
}
int main()
{
Test();
return 0;
#include <iostream>
using namespace std;
char *GetMemory(void)
{
char p[]="hello world";
return p;
}
void Test(void)
{
char *str=NULL;
str=GetMemory();
printf(str);
}
int main()
{
Test();
return 0;
#include <iostream>
using namespace std;
void GetMemory(char **p,int num)
{
*p=(char *)malloc(num);
}
void Test(void)
{
char *str=NULL;
GetMemory(&str,100);
strcpy(str,"hello");
printf(str);
}
int main()
{
Test();
return 0;
#include <iostream>
using namespace std;
void Test(void)
{
char *str=(char *)malloc(100);
strcpy(str,"hello");
free(str);
if(str!=NULL)
{
strcpy(str,"world");
printf(str);
}
}
int main()
{
Test();
return 0;
#include <iostream>
using namespace std;
void GetMemory(char *p)
{
p=(char *)malloc(100);
}
void Test(void)
{
char *str=NULL;
GetMemory(str);
strcpy(str,"Hello world");
printf(str);
}
int main()
{
Test();
return 0;
}
运行Test函数后结果:程序崩溃。因为GetMemory并不能传递动态内存,Test函数中str一直是NULL。strcpy(str,"hello world")后系统崩溃
2#include <iostream>
using namespace std;
char *GetMemory(void)
{
char p[]="hello world";
return p;
}
void Test(void)
{
char *str=NULL;
str=GetMemory();
printf(str);
}
int main()
{
Test();
return 0;
}
运行Test函数后:乱码。因为GetMemory返回的是指向"栈内存”的指针,该指针不是NULL,但原先的内容已经被清除,新内容不可知
3#include <iostream>
using namespace std;
void GetMemory(char **p,int num)
{
*p=(char *)malloc(num);
}
void Test(void)
{
char *str=NULL;
GetMemory(&str,100);
strcpy(str,"hello");
printf(str);
}
int main()
{
Test();
return 0;
}
运行Test后:能够输出hello ,内存泄漏(不知道这个名词的百度一下可能会更明白)。
4#include <iostream>
using namespace std;
void Test(void)
{
char *str=(char *)malloc(100);
strcpy(str,"hello");
free(str);
if(str!=NULL)
{
strcpy(str,"world");
printf(str);
}
}
int main()
{
Test();
return 0;
}
运行Test后:篡改了动态内存区的内容,后果难以预料,非常危险。因为free(str)后,str变为野指针,if(str!=NULL)语句不起作用。(不明白的可以百度一下 什么是野指针,这里不做过多的解释)
以上的4个程序均在VC++6.0上调试通过。
- C--有关内存的思考
- C++中有关内存的思考
- 个人有关内存的思考:
- 有关内存池的思考
- 有关内存的思考?GetMemory()
- 有关C语言中bool类型的思考
- 有关思考的思考
- c有关内存的函数
- C有关内存的思考题
- 设计中有关折中的思考
- 黑马程序员--有关OC内存管路set方法的思考
- c语言有关内存的问题
- C语言 有关内存的思考题
- C C++有关内存的思考题
- 有关LKML的思考
- 有关数据库的思考
- 有关职业规划的思考
- 有关C语言运算符优先级和结合律的思考
- java调用c++动态库dll
- 一个文件中有40亿个整数,求出这个文件里的整数里不包含的一个整数
- 最小生成树
- Firefox保存网页预览模式下的图片方法
- c++中的explicit关键字及隐式类型转换
- C++中有关内存的思考
- 在一个文件中有10G个整数,乱序排列,要求找出中位数
- ITK VTK CTK QT 跨平台联合开发之 四 <Mac OS X篇>
- 递归--阶乘
- 图像处理特征不变算子系列之KLT算子--GoodFeaturesToTrack(七)
- 【梦幻童年win7热门主题】
- hashtable的C++实现
- static
- 2009-12-03 10:34 HTTP请求错误400、401、402、403、404、405、406、407、412、414、500、501、502解析