試題4:
void GetMemory( char *p ) { p = (char *) malloc( 100 ); }
void Test( void ) { char *str = NULL; GetMemory( str ); strcpy( str, "hello world" ); printf( str ); } |
試題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 ); } |
試題7:
void Test( void ) { char *str = (char *) malloc( 100 ); strcpy( str, "hello" ); free( str ); ... //省略的其它語句 } |
解答:
試題4傳入中GetMemory( char *p )函數(shù)的形參為字符串指針,在函數(shù)內(nèi)部修改形參并不能真正的改變傳入形參的值,執(zhí)行完
char *str = NULL; GetMemory( str ); |
后的str仍然為NULL;
試題5中
char p[] = "hello world"; return p; |
的p[]數(shù)組為函數(shù)內(nèi)的局部自動(dòng)變量,在函數(shù)返回后,內(nèi)存已經(jīng)被釋放。這是許多程序員常犯的錯(cuò)誤,其根源在于不理解變量的生存期。
試題6的GetMemory避免了試題4的問題,傳入GetMemory的參數(shù)為字符串指針的指針,但是在GetMemory中執(zhí)行申請(qǐng)內(nèi)存及賦值語句
*p = (char *) malloc( num ); |
后未判斷內(nèi)存是否申請(qǐng)成功,應(yīng)加上:
if ( *p == NULL ) { ...//進(jìn)行申請(qǐng)內(nèi)存失敗處理 } |
試題7存在與試題6同樣的問題,在執(zhí)行
char *str = (char *) malloc(100); |
后未進(jìn)行內(nèi)存是否申請(qǐng)成功的判斷;
另外,在free(str)后未置str為空,導(dǎo)致可能變成一個(gè)“野”指針,應(yīng)加上:
試題6的Test函數(shù)中也未對(duì)malloc的內(nèi)存進(jìn)行釋放。
剖析:
試題4~7考查面試者對(duì)內(nèi)存操作的理解程度,基本功扎實(shí)的面試者一般都能正確的回答其中50~60的錯(cuò)誤。但是要完全解答正確,卻也絕非易事。
對(duì)內(nèi)存操作的考查主要集中在:
(1)指針的理解;
(2)變量的生存期及作用范圍;
(3)良好的動(dòng)態(tài)內(nèi)存申請(qǐng)和釋放習(xí)慣。
再看看下面的一段程序有什么錯(cuò)誤:
swap( int* p1,int* p2 ) { int *p; *p = *p1; *p1 = *p2; *p2 = *p; } |
在swap函數(shù)中,p是一個(gè)“野”指針,有可能指向系統(tǒng)區(qū),導(dǎo)致程序運(yùn)行的崩潰。在VC++中DEBUG運(yùn)行時(shí)提示錯(cuò)誤“Access Violation”。該程序應(yīng)該改為:
swap( int* p1,int* p2 ) { int p; p = *p1; *p1 = *p2; *p2 = p; } |