代碼的問題:
- 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 );
}