Chinaunix首页 | 论坛 | 博客
  • 博客访问: 175113
  • 博文数量: 65
  • 博客积分: 1790
  • 博客等级: 上尉
  • 技术积分: 460
  • 用 户 组: 普通用户
  • 注册时间: 2010-09-21 23:51
文章分类
文章存档

2012年(8)

2011年(38)

2010年(19)

分类: C/C++

2011-02-24 23:42:44

1,

void getMemory(char *p, int num)
{
  p=(char *)malloc(sizeof(char)*num);
}


void test(void)
{
  char *str=NULL;
  getMemory(str,100);//str仍然为NULL
  strcpy(str,"hello");//运行错误
}

指针p的副本_p被重新分配内存,并且p未被free,造成内存泄漏。

2,

char *getString(void)
{
  char p[]="hello world";
  return p;
}
void test4(void)
{
  char *str=NULL;
  str=getString();//str的内容是垃圾
  cout<}

return返回栈内存,函数返回时会自动消亡,str内容是垃圾。

3,

 char *p=(char *)malloc(100);
 strcpy(p,"hello");
 free(p);
 if(p!=NULL)
 {
   cout<   strcpy(p,"world");//出错
   cout< }

指针p被free之后其地址不变,只是地址的内存为垃圾。必须设置p为NULL,避免成为野指针。

阅读(685) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~