試題
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 );
? ???...??//
省略的其它語(yǔ)句
}
解答:
試題
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
的問(wèn)題,傳入
GetMemory
的參數(shù)為字符串指針的指針,但是在
GetMemory
中執(zhí)行申請(qǐng)內(nèi)存及賦值語(yǔ)句
p = (char *) malloc( num );
后未判斷內(nèi)存是否申請(qǐng)成功,應(yīng)加上:
if ( p == NULL )
{
? ?...//
進(jìn)行申請(qǐng)內(nèi)存失敗處理
}
試題
7
存在與試題
6
同樣的問(wèn)題,在執(zhí)行
char *str = (char *) malloc(100);
后未進(jìn)行內(nèi)存是否申請(qǐng)成功的判斷;另外,在
free(str)
后未置
str
為空,導(dǎo)致可能變成一個(gè)
“
野
”
指針,應(yīng)加上:
str = NULL;
試題
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;
}
posted on 2006-11-09 15:47
喬棟 閱讀(377)
評(píng)論(0) 編輯 收藏 引用 所屬分類:
C的游樂(lè)園