其他语言

本类阅读TOP10

·基于Solaris 开发环境的整体构思
·使用AutoMake轻松生成Makefile
·BCB数据库图像保存技术
·GNU中的Makefile
·射频芯片nRF401天线设计的分析
·iframe 的自适应高度
·BCB之Socket通信
·软件企业如何实施CMM
·入门系列--OpenGL最简单的入门
·WIN95中日志钩子(JournalRecord Hook)的使用

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
free struct,内部指针并不free

作者:未知 来源:月光软件站 加入时间:2005-2-28 月光软件站

C的struct有大缺陷,其内存管理就是一个问题,free掉一个struct结构的指针,如果其struct内部有指针,该指针内容不释放,这个在调用别人写好的struct接口时,会相当麻烦,这就要求对方除了提供struct接口外,还提供额外的内存管理支持,否则很容易出现问题,在这点上,C++的构造函数、析构函数明显表现要好的多,下面是一个free struct的C的例子:

#include
#include

struct test
{
 char* p_ch;
 int ix;
};

int main(int argc, char *argv[])
{
 struct test *p_test;
 p_test = malloc(sizeof(struct test));
 p_test->p_ch = malloc(20);
 char *p_ch = "Hello!";
 strcpy(p_test->p_ch, p_ch);
 p_ch = p_test->p_ch;
 printf("p_test->p_ch:\t%s\n", p_test->p_ch);
 free(p_test->p_ch); //如果注释掉这行,p_ch值仍为“Hello!” 
  free(p_test);
 printf("after free(p_test), p_ch:\t%s\n", p_ch);
 

 system("PAUSE");?
 return 0;
}




相关文章

相关软件