代码的问题:
- GetMemory以拷贝的形式传入实参,即将实参str指针的值赋值给了形参p,在函数内部对形参进行的更改,不会影响实参的变化,因此str仍然为NULL;
- 没有释放内存;
void GetMemory( char *p )
{
p = (char *) malloc( 100 );
}
void Test( void )
{
char *str = NULL;
GetMemory( str );
strcpy( str, "hello world" );
printf( str );
}
代码的问题:
- 形参为指针的指针p,实参传入的也是指针str的指针&str,将&str拷贝传给p,对p解引用得到的就是指针str,因此str会被申请内存;
- 申请内存后,应该判断内存是否申请成功;
- 确保num>0;
- 内存没有释放;
void GetMemory( char **p, int num )
{
*p = (char *) malloc( num );
}
void Test( void )
{
char *str = NULL;
GetMemory( &str, 100 );
strcpy( str, "hello" );
printf( str );
}