『EXP2』关于在函数内部分配内存时需要注意的问题

来源:互联网 发布:php源代码加密 编辑:程序博客网 时间:2024/05/17 03:45

char*    buff;

int  lenth = INTVAL;

NewFunc( ?, INTVAL );   // 这里应该怎么写?

//  NewFunc()应该如何声明?

先说NewFunc( )函数的声明和定义,声明如下:

int   NewFunc( char** Buff, int BuffSize );

定义如下: 

int    NewFunc( char** Buff, int BuffSize )

{

     char*  tempBuff = NULL;      // 如果直接 *Buff = new char[BuffSize];,

                                  // 如果申请失败还须将*Buff设为NULL

     try{

         tempBuff = new char[BuffSize];

     }

     catch(...){

          return -1;

     }

     *Buff = tempBuff;    // 内存申请成功后再将内存交给外部

     return 0;

}

int    NewFunc( char** Buff, int BuffSize )

{

     char*  tempBuff = NULL;      // 如果直接 *Buff = new char[BuffSize];,

                                  // 如果申请失败还须将*Buff设为NULL

     try{

         tempBuff = new char[BuffSize];

     }

     catch(...){

          return -1;

     }

     *Buff = tempBuff;    // 内存申请成功后再将内存交给外部

     return 0;

}

参数Buff是二级指针

调用NewFunc( )的方法如下:

   NewFunc( *buff, INTVAL);

原创粉丝点击