GetMemory函式詳解

2021-06-29 02:36:01 字數 2304 閱讀 2848

#include

#include

#include

using namespace std;

char *getmemory(char *&p, int num)

int main(void)

getmemory錯誤講解(指標練習) 錯誤程式:

void getmemory( char *p )

void test( void )

這個乙個考驗對指標理解的題目,上面程式在執行之後:

1,呼叫getmemory( str )後, str並未產生變化,依然是null.只是改變的str的乙個拷貝的記憶體的變化   

2,strcpy( str, "hello world" );程式執行到這將產生錯誤。

3,new的時候有可能記憶體出錯,應該在*p = (char *) malloc( num ); 後判斷記憶體是否申請成功,應加上:

if ( *p == null )

4,動態建立的記憶體沒釋放。

錯誤分析:

錯認為 getmemory(char   *p)中的 p 「就是」 getmemory(str)中的str。但p「不是」str,它只是「等於」str 。

就象:   int   a   =   100;  

int   b   =   a;       //   現在b等於a  

b   =   500;         //   現在能認為a   =   500 ?     

顯然不能認為a   =   500,因為b只是等於a,但不是a! 當b改變的時候,a並不會改變,b就不等於a了。    因此,雖然p已經有new的記憶體,但str仍然是null  

getmemory(str);             //把str傳進去,str是乙個指標,而他實際上是乙個int     

void   getmemory(char   *p)     //   p是str的乙個副本  

而雙重指標為什麼就可以了呢:  

getmemory(&str);             //把str的位址傳進去      

void   getmemory(char   **   p)     //   p是str位址的乙個副本  

void getmemory2(char **p)變為二級指標.

void getmemory2(char **p, int num)

void test(void)

修改方法2:

char *getmemory()

void test(void)

試題5:

char *getmemory( void )

void test( void )

試題6:

void getmemory( char **p, int num )

void test( void )

試題7:

void test( void )

解答:試題5中

char p = "hello world";

return p;

的p陣列為函式內的區域性自動變數,在函式返回後,記憶體已經被釋放。這是許多程式設計師常犯的錯誤,其根源在於不理解變數的生存期。

試題6中

1、getmemory避免了試題4的問題,傳入getmemory的引數為字串指標的指標,但是在getmemory中執行申請記憶體及賦值語句

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

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

if ( *p == null )

2、試題6的test函式中也未對malloc的記憶體進行釋放。

試題7中

存在與試題6同樣的問題,在執行

char *str = (char *) malloc(100); 後未進行記憶體是否申請成功的判斷;另外,在free(str)後未置str為空,導致可能變成乙個「野」指標,應加上: str = null;

剖析:試題4~7考查面試者對記憶體操作的理解程度,基本功紮實的面試者一般都能正確的回答其中50~60的錯誤。但是要完全解答正確,卻也絕非易事。

對記憶體操作的考查主要集中在:

(1)指標的理解;

(2)變數的生存期及作用範圍;

(3)良好的動態記憶體申請和釋放習慣。

再看看下面的一段程式有什麼錯誤:

swap( int* p1,int* p2 )

在swap函式中,p是乙個「野」指標,有可能指向系統區,導致程式執行的崩潰。在vc++中debug執行時提示錯誤「access violation」。該程式應該改為:

swap( int* p1,int* p2 )

GetMemory函式詳解

void getmemory char p void test 實質 getmemory str 在呼叫時會生成乙個 str與str指向同乙個數,這是因為c語言中函式傳遞形參不改變實參的內容,但是指標指向的內容是相同的,因此可以用指標控制資料。題中的getmemory str 實質是對 str的操作...

筆試題 GetMemory 函式

void getmemory char p p char malloc 100 void test char str null getmemory str strcpy str,helloworld printf str 實質 getmemory str 在呼叫時會生成乙個 str與str指向同乙個...

GetMemory函式的幾種經典考法

void getmemory char p int main int argc,char argv str沒有得到分配記憶體的位址值。記憶體空間狀態 首先申請了四個位元組的棧空間,存放str指標,此時str的值為0,存放str的這塊記憶體的位址值為0x0012ff7c。呼叫函式 getmemory,...