筆試題 GetMemory 函式

2021-07-10 10:07:14 字數 1669 閱讀 4376

void getmemory(char *p)

p=(char *)malloc(100);

void test()

char *str=null;

getmemory(str);

strcpy(str,"helloworld");

printf(str);

實質:getmemory(str)在呼叫時會生成乙個_str與str指向同乙個數,這是因為c語言中函式傳遞形參不改變實參的內容,但是指標指向的內容是相同的,因此可以用指標控制資料。題中的getmemory(str),實質是對_str的操作,並沒有對str操作,函式結束後_str撤銷,因此不會產生新的記憶體空間,str仍然是乙個空指標。

要在函式內部改變某個變數的值,使之能在出了這個函式後,剛才的改變仍然有效,那就必須通過引數傳入「指向這個變數的指標」,而不是變數本身。也就是說,任何函式都不能把對引數本身的改變帶到函式體外,所改的只是這個引數所指向的變數的值。

void func1(char *p)

int main()

void func2(char **p)

int main()

no2char *getmemory()

char p="hello world";

return p;

void test()

char * str=null;

str=getmemory();

printf(str);

no3char *getmemory()

return 「hello world」;

void test()

char * str=null;

str=getmemory();

printf(str);

no4void getmemory(char **p,int num)

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

void test()

char * str=null;

getmemory(&str,100);

strcpy(str,"hello");

printf(str);

可以正確的列印hello但是記憶體洩露了,在getmemory()中使用了malloc申請記憶體,但是在最後卻沒有對申請的記憶體做任何處理,因此可能導致記憶體的洩露,非常危險。

no5void test()

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

strcpy(str,"hello");

free(str);

if (str!=null)

申請空間,拷貝字串,釋放空間,前三步操作都沒有問題,到了if語句裡的判斷條件開始出錯了。因為乙個指標被釋放了之後其內容並不是null,而是乙個不確定的值,所以if語句永遠不能被執行(注:strcpy(str,"world")有風險),這也是著名的「野」指標問題。

no6void getmemory(void)

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

strcpy(str,"hello");

free(str);

if (str !=null)

str 為野指標,列印的結果不能確定。

GetMemory函式詳解

include include include using namespace std char getmemory char p,int num int main void getmemory錯誤講解 指標練習 錯誤程式 void getmemory char p void test void 這...

GetMemory函式詳解

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

js函式筆試題

一丶var a b 4 function console.log a 4 console.log b 6在全域性作用域裡面a和b都被賦值為4,在進去立即執行函式後首先賦值的是給全域性的b 6,在給區域性作用域的var a b,同樣是6,執行完了之後立即執行函式消失,最後要輸出的是全域性的a和b所以是...