一个关于malloc的面试题
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
前兩天看了一個(gè)關(guān)于malloc的面試題,題目是這樣的:
void GetMemory(char *p , int nlen) {p = (char*)malloc(nlen); } void main() {char* str=NULL;GetMemory(str , 11);strcpy(str, "hello world");printf(str); }
對(duì)于這個(gè)問(wèn)題,我第一眼看到的是,字符串長(zhǎng)度的問(wèn)題和malloc出來(lái)的內(nèi)存塊沒(méi)有free的問(wèn)題。字符串”hello world”在結(jié)尾包含一個(gè)’\0’ ,所以長(zhǎng)度為12,而malloc出來(lái)的內(nèi)存塊必須要free掉,不然就會(huì)出現(xiàn)野指針。這兩兩個(gè)問(wèn)題比較好看出來(lái)。
但是這都不是問(wèn)題的關(guān)鍵,問(wèn)題的關(guān)鍵在于函數(shù)的傳值,我們要改變實(shí)參的值,傳入的必須是引用類(lèi)型和指針類(lèi)型。
str也確實(shí)是一個(gè)指針,但是當(dāng)我們需要改變這個(gè)指針的值的時(shí)候,我們必須傳入str的地址即&str;所以GetMemory的正確寫(xiě)法應(yīng)該是:
void GetMemory(char **p , int nlen) {*p = (char*)malloc(nlen); }
完整程序:
#include"stdio.h" #include"string.h" #include"stdlib.h"void GetMemory(char **p , int nlen) {*p = (char*)malloc(nlen); }Void main() {char* str = NULL;GetMemory(&str , 128);strcpy(str , "hello world");printf(str);free(str); }
轉(zhuǎn)載于:https://my.oschina.net/u/586637/blog/217710
總結(jié)
以上是生活随笔為你收集整理的一个关于malloc的面试题的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Struct2小结:
- 下一篇: POJ 3617 Best Cow Li