天天看點

四道經典C語言指針試題試題一:試題二:試題三:試題四:

四道經典C語言指針試題

void GetMemory( char *p )

{

 p = (char *) malloc( 100 );

}

void Test( void )

 char *str = NULL;

 GetMemory( str );

 strcpy( str, "hello world" );

 printf( str );

本題中傳入中GetMemory( char *p )函數的形參為字元串指針,在函數内部修改形參并不能真正的改變傳入形參的值,執行完

char *str = NULL;

GetMemory( str ); 

後的str仍然為NULL;

存在記憶體洩露,列印為空

char *GetMemory( void )

 char p[] = "hello world";

 return p;

 str = GetMemory();

char p[] = "hello world";

return p; 

p[]數組為函數内的局部自動變量,在函數傳回後,記憶體已經被釋放。這是許多程式員常犯的錯誤,其根源在于不了解變量的生存期。

void GetMemory( char **p, int num )

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

 GetMemory( &str, 100 );

 strcpy( str, "hello" );

存在2處問題:

本題中的Test函數中未對malloc的記憶體進行釋放。

本題中的GetMemory避免了試題一的問題,傳入GetMemory的參數為字元串指針的指針,但是在GetMemory中執行申請記憶體及指派語句

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

後未判斷記憶體是否申請成功,應加上:

if ( *p == NULL )

 ...//進行申請記憶體失敗處理

 char *str = (char *) malloc( 100 );

 free( str );

 ... //省略的其它語句

試題四存在與試題三同樣的問題,在執行char *str = (char *) malloc(100);

後未進行記憶體是否申請成功的判斷;

另外,在free(str)後未置str為空,導緻可能變成一個“野”指針,應加上:

str = NULL;

繼續閱讀