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

2012年(8)

2011年(38)

2010年(19)

分类: C/C++

2012-03-11 23:57:59

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,避免成为野指针。


4,


void GetMemory( char **p, int num )


{


    *p = (char *) malloc( num );


}


void Test_6( void )


{


    char *str = NULL;


    GetMemory( &str, 100 );


    strcpy( str, "hello" );


    printf( str );


}


分析:传入指针的指针,


阅读(1191) | 评论(0) | 转发(0) |
0

上一篇:链表

下一篇:深入探讨C++中的引用

给主人留下些什么吧!~~