有關記憶體的思考題

2021-05-22 15:51:10 字數 2158 閱讀 9696

摘自《高質量c、c++程式設計指南》

四、有關記憶體的思考題(20 分)

void getmemory(char *p)

p = (char *)malloc(100);

void test(void)

char *str = null;

getmemory(str);

strcpy(str, "hello world");

printf(str);

請問執行test 函式會有什麼樣的結果?

答:char *getmemory(void)

char p = "hello world";

return p;

void test(void)

char *str = null;

str = getmemory();

printf(str);

請問執行test 函式會有什麼樣的結果?

答:void getmemory2(char **p, int num)

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

void test(void)

char *str = null;

getmemory(&str, 100);

strcpy(str, "hello");

printf(str);

請問執行test 函式會有什麼樣的結果?

答:void test(void)

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

strcpy(str, 「hello」);

free(str);

if(str != null)

strcpy(str, 「world」);

printf(str);

請問執行test 函式會有什麼樣的結果?

答:解答如下:

void getmemory(char *p)

p = (char *)malloc(100);

void test(void)

char *str = null;

getmemory(str);

strcpy(str, "hello world");

printf(str);

請問執行test 函式會有什麼樣的結果?

答:程式崩潰。

因為getmemory 並不能傳遞動態記憶體,

test 函式中的 str 一直都是 null。

strcpy(str, "hello world");將使程式崩

潰。char *getmemory(void)

char p = "hello world";

return p;

void test(void)

char *str = null;

str = getmemory();

printf(str);

請問執行test 函式會有什麼樣的結果?

答:可能是亂碼。

因為getmemory 返回的是指向「棧記憶體」

的指標,該指標的位址不是 null,但其原

現的內容已經被清除,新內容不可知。

void getmemory2(char **p, int num)

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

void test(void)

char *str = null;

getmemory(&str, 100);

strcpy(str, "hello");

printf(str);

請問執行test 函式會有什麼樣的結果?

答:(1)能夠輸出hello

(2)記憶體洩漏

void test(void)

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

strcpy(str, 「hello」);

free(str);

if(str != null)

strcpy(str, 「world」);

printf(str);

請問執行test 函式會有什麼樣的結果?

答:篡改動態記憶體區的內容,後果難以預

料,非常危險。

因為free(str);之後,str 成為野指標,

if(str != null)語句不起作用。

有關記憶體的思考題

void getmemory char p void test void 請問執行test 函式會有什麼樣的結果?因為 getmemory 並不能傳遞動態記憶體,test 函式中的 str 一直都是 null。strcpy str,hello world 將使程式崩潰。2.char getmemor...

有關記憶體的思考題

注意下面4個測試函式的執行結果 測試函式1 void getmemory char p void test void 執行結果 程式崩潰。因為getmemory並不能傳遞動態記憶體,test函式中的str一直都是null。strcpy str,hello world 將使程式崩潰。測試函式2 cha...

C有關記憶體的思考題

void getmemery char p void test int main 請問執行test函式會有什麼樣的結果?下面是在windows下vs2013編譯器的結果 程式崩潰 因為getmemory方法並不能傳遞動態記憶體 test函式中的str一直都是null strcpy將使程式崩潰 之所以...