1:传递指针的地址;
2:释放内存;
3:野指针;
试题4:void GetMemory( char *p )
{
p = (char *) malloc( 100 );//在函数内部修改形参并不能真正的改变传入形参的值
}
void Test( void )
{
char *str = NULL;
GetMemory( str );
strcpy( str, "hello world" );
printf( str );
}
试题4传入中GetMemory( char *p )函数的形参为字符串指针,在函数内部修改形参并不能真正的改变传入形参的值,执行完char *str = NULL;
GetMemory( str );
后的str仍然为NULL;
试题5:
char *GetMemory( void )
{
char p[] = "hello world";
return p;
}
void Test( void )
{
char *str = NULL;
str = GetMemory();
printf( str );
}
试题6:void GetMemory( char **p, int num )
{
*p = (char *) malloc( num );
}
void Test( void )
{
char *str = NULL;
GetMemory( &str, 100 );
strcpy( str, "hello" );
printf( str );
}
试题6的GetMemory避免了试题4的问题,传入GetMemory的参数为字符串指针的指针,但是在GetMemory中执行申请内存及赋值语句*p = (char *) malloc( num );
后未判断内存是否申请成功,应加上:if ( *p == NULL )
{
...//进行申请内存失败处理
}
另外,Test函数中也未对malloc的内存进行释放;
试题7:void Test( void )
{
char *str = (char *) malloc( 100 );
strcpy( str, "hello" );
free( str );
... //省略的其它语句
}
在free(str)后未置str为空,导致可能变成一个“野”指针,应加上:
str = NULL;