面试官问:malloc(0)时程序会返回什么?
今天跟大家找了篇文章,主要是一個面試中的有趣問題,其實有些問題在開發中沒有遇到過會很難回答出來,如果在面試過程中回答正確,皆大歡喜,拿到offer的概率更大;回答不出來也不要信口開河,面試官主要看的是你對待問題的態度~
正文:
故事要從前兩天交流群中一位同學提到的這個問題開始
這個問題看起來十分刁鉆,不過稍有常識的人都知道,制定 C 標準的那幫語言律師也不是吃白飯的,對這種奇奇怪怪的問題一定會有定義。翻閱C17 標準 草案 N2176,在 7.22.3 節里,有如下說法:
The order and contiguity of storage allocated by successive calls to the aligned_alloc, calloc, malloc, and realloc functions is unspecified. The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object with a fundamental alignment requirement and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated). The lifetime of an allocated object extends from the allocation until the deallocation. Each such allocation shall yield a pointer to an object disjoint from any other object. The pointer returned points to the start (lowest byte address) of the allocated space. If the space cannot be allocated, a null pointer is returned. If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned to indicate an error, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.
在這里,標準委員會明確規定了:當 malloc 接到的參數為 0 時,其行為是由實現定義的(implementation-defined)。
由實現定義的行為這個詞就提醒我們,在實際編程時如果要考慮到程序在多個運行環境下進行運行時,不能對 malloc 返回的數值進行任何假設。
換言之,沒事兒不要吃飽了撐的在實際編程中寫下 malloc(0) 這種天怒人怨的代碼。
但是,這個無意義的問題吸引了我的興趣。因此我開始查閱 glibc 的源代碼,依此了解在 glibc 下,mallloc(0) 的行為。在 glibc2.27/malloc/malloc.c 中,有如下注釋:
/*malloc(size_t?n)Returns?a?pointer?to?a?newly?allocated?chunk?of?at?least?n?bytes,?or?nullif?no?space?is?available.?Additionally,?on?failure,?errno?isset?to?ENOMEM?on?ANSI?C?systems.If?n?is?zero,?malloc?returns?a?minumum-sized?chunk.?(The?minimumsize?is?16?bytes?on?most?32bit?systems,?and?24?or?32?bytes?on?64bitsystems.)??On?most?systems,?size_t?is?an?unsigned?type,?so?callswith?negative?arguments?are?interpreted?as?requests?for?huge?amountsof?space,?which?will?often?fail.?The?maximum?supported?value?of?ndiffers?across?systems,?but?is?in?all?cases?less?than?the?maximumrepresentable?value?of?a?size_t. */注釋已經說的很清楚了,當我們執行 malloc(0) 時,我們實際會拿到一個指向一小塊內存的指針,這個指針指向的(分配給我們的)內存的大小是由機器決定的。
細讀代碼,可以發現,將讀入的內存大小進行轉換是由宏 checked_request2size 實現的。
相關的宏定義如下:
/*?pad?request?bytes?into?a?usable?size?--?internal?version?*/ #define?request2size(req)?????????????????????????????????????????\(((req)?+?SIZE_SZ?+?MALLOC_ALIGN_MASK?<?MINSIZE)????????????????\MINSIZE?:??????????????????????????????????????????????????????\((req)?+?SIZE_SZ?+?MALLOC_ALIGN_MASK)?&?~MALLOC_ALIGN_MASK)/*?Same,?except?also?perform?an?argument?and?result?check.??First,?we?checkthat?the?padding?done?by?request2size?didn't?result?in?an?integeroverflow.??Then?we?check?(using?REQUEST_OUT_OF_RANGE)?that?the?resultingsize?isn't?so?large?that?a?later?alignment?would?lead?to?another?integeroverflow.??*/#define?checked_request2size(req,?sz)?\ ({????????\(sz)?=?request2size?(req);?????\if?(((sz)?<?(req))??????\||?REQUEST_OUT_OF_RANGE?(sz))?\{????????\__set_errno?(ENOMEM);?????\return?0;???????\}????????\ })也就是說,我們能申請到的數值最小為 MINSIZE ,這個 MINSIZE 的相關定義如下:
/*?The?smallest?possible?chunk?*/ #define?MIN_CHUNK_SIZE????????(offsetof(struct?malloc_chunk,?fd_nextsize)) /*?The?smallest?size?we?can?malloc?is?an?aligned?minimal?chunk?*/ #define?MINSIZE??\(unsigned?long)(((MIN_CHUNK_SIZE+MALLOC_ALIGN_MASK)?&?~MALLOC_ALIGN_MASK))/*?The?corresponding?bit?mask?value.??*/ #define?MALLOC_ALIGN_MASK?(MALLOC_ALIGNMENT?-?1) /*?MALLOC_ALIGNMENT?is?the?minimum?alignment?for?malloc'ed?chunks.??Itmust?be?a?power?of?two?at?least?2?*?SIZE_SZ,?even?on?machines?forwhich?smaller?alignments?would?suffice.?It?may?be?defined?as?largerthan?this?though.?Note?however?that?code?and?data?structures?areoptimized?for?the?case?of?8-byte?alignment.??*/ #define?MALLOC_ALIGNMENT?(2?*?SIZE_SZ?<?__alignof__?(long?double)?\??__alignof__?(long?double)?:?2?*?SIZE_SZ)#ifndef?INTERNAL_SIZE_T #?define?INTERNAL_SIZE_T?size_t #endif/*?The?corresponding?word?size.??*/ #define?SIZE_SZ?(sizeof?(INTERNAL_SIZE_T))/*This?struct?declaration?is?misleading?(but?accurate?and?necessary).It?declares?a?"view"?into?memory?allowing?access?to?necessaryfields?at?known?offsets?from?a?given?base.?See?explanation?below. */struct?malloc_chunk?{INTERNAL_SIZE_T??????mchunk_prev_size;??/*?Size?of?previous?chunk?(if?free).??*/INTERNAL_SIZE_T??????mchunk_size;???????/*?Size?in?bytes,?including?overhead.?*/struct?malloc_chunk*?fd;?????????/*?double?links?--?used?only?if?free.?*/struct?malloc_chunk*?bk;/*?Only?used?for?large?blocks:?pointer?to?next?larger?size.??*/struct?malloc_chunk*?fd_nextsize;?/*?double?links?--?used?only?if?free.?*/struct?malloc_chunk*?bk_nextsize; };//?GCC?提供 /*?Offset?of?member?MEMBER?in?a?struct?of?type?TYPE.?*/ #define?offsetof(TYPE,?MEMBER)?__builtin_offsetof?(TYPE,?MEMBER)至此,我們就可以根據這些計算出使用 glibc 在我們的電腦上運行時 malloc 出的最小空間的大小了。計算完后,還可以根據 malloc_usable_size 判斷自己的計算是否正確,樣例代碼如下:
#include?<stdio.h> #include?<malloc.h> int?main(void)?{char?*p?=?malloc(0);printf("Address:?0x%x.\nLength:?%ld.\n",p,malloc_usable_size(p));return?0; }該樣例在我電腦內輸出的結果為 24。
因此,我們知道了,在 glibc 下,執行 malloc 會得到一個指向分配給我們的大小為 24 字節的內存空間的指針。
但這只是在 glibc 下的結果,在其他 C 標準庫實現內,可能你會得到一個空指針。因為標準中提到了,對于 malloc(0) 這種故意挑事的代碼,實現時可以返回一個空指針作為回禮。
素材源于:文章來源:https://zhuanlan.zhihu.com/p/40490357
直接來源:嵌入式與linux那些事
版權歸原作者所有。僅供技術的傳播和學習討論,如涉及作品版權問題,請聯系我進行刪除。
推薦閱讀:
專輯|Linux文章匯總
專輯|程序人生
專輯|C語言
我的知識小密圈
關注公眾號,后臺回復「1024」獲取學習資料網盤鏈接。
歡迎點贊,關注,轉發,在看,您的每一次鼓勵,我都將銘記于心~
總結
以上是生活随笔為你收集整理的面试官问:malloc(0)时程序会返回什么?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 这三个Offer,你怎么选?
- 下一篇: 海康威视网络摄像头开发流程(七)----