衡阳派盒市场营销有限公司

0
  • 聊天消息
  • 系統消息
  • 評論與回復
登錄后你可以
  • 下載海量資料
  • 學習在線課程
  • 觀看技術視頻
  • 寫文章/發帖/加入社區
會員中心
創作中心

完善資料讓更多小伙伴認識你,還能領取20積分哦,立即完善>

3天內不再提示

面試題:malloc(0)會發生什么?

STM32嵌入式開發 ? 來源:STM32嵌入式開發 ? 2023-10-31 16:27 ? 次閱讀

故事要從前兩天交流群中一位同學提到的這個問題開始:

e80411b4-77c2-11ee-939d-92fbcf53809c.png

這個問題看起來十分刁鉆,不過稍有常識的人都知道,制定 C 標準的那幫語言律師也不是吃白飯的,對這種奇奇怪怪的問題一定會有定義。翻閱C17 標準 草案 N2176,在 7.22.3 節里,有如下說法:

The order and contiguity of storage allocated by successivecalls 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 null
  if no space is available. Additionally, on failure, errno is
  set to ENOMEM on ANSI C systems.


  If n is zero, malloc returns a minumum-sized chunk. (The minimum
  size is 16 bytes on most 32bit systems, and 24 or 32 bytes on 64bit
  systems.)  On most systems, size_t is an unsigned type, so calls
  with negative arguments are interpreted as requests for huge amounts
  of space, which will often fail. The maximum supported value of n
  differs across systems, but is in all cases less than the maximum
  representable 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 check
   that the padding done by request2size didn't result in an integer
   overflow.  Then we check (using REQUEST_OUT_OF_RANGE) that the resulting
   size isn't so large that a later alignment would lead to another integer
   overflow.  */


#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.  It
   must be a power of two at least 2 * SIZE_SZ, even on machines for
   which smaller alignments would suffice. It may be defined as larger
   than this though. Note however that code and data structures are
   optimized 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 necessary
  fields 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 
#include 
int main(void) {
    char *p = malloc(0);
    printf("Address: 0x%x.
Length: %ld.
",p,malloc_usable_size(p));
    return 0;
}

該樣例在我電腦內輸出的結果為 24。

因此,我們知道了,在 glibc 下,執行 malloc 會得到一個指向分配給我們的大小為 24 字節的內存空間的指針。

但這只是在 glibc 下的結果,在其他 C 標準庫實現內,可能你會得到一個空指針。因為標準中提到了,對于 malloc(0) 這種故意挑事的代碼,實現時可以返回一個空指針作為回禮。


聲明:本文內容及配圖由入駐作者撰寫或者入駐合作網站授權轉載。文章觀點僅代表作者本人,不代表電子發燒友網立場。文章及其配圖僅供工程師學習之用,如有內容侵權或者其他違規問題,請聯系本站處理。 舉報投訴
  • 程序
    +關注

    關注

    117

    文章

    3796

    瀏覽量

    81419
  • 源代碼
    +關注

    關注

    96

    文章

    2946

    瀏覽量

    66960
  • Glibc
    +關注

    關注

    0

    文章

    9

    瀏覽量

    7525
  • malloc
    +關注

    關注

    0

    文章

    53

    瀏覽量

    82

原文標題:面試題:malloc(0)會發生什么?

文章出處:【微信號:c-stm32,微信公眾號:STM32嵌入式開發】歡迎添加關注!文章轉載請注明出處。

收藏 人收藏

    評論

    相關推薦

    常見的嵌入式C語言面試題

    數組是最基本的數據結構,關于數組的面試題也屢見不鮮,本文羅列了一些常見的面試題,僅供參考。目前有以下18道題目。
    發表于 07-18 10:46 ?839次閱讀

    java基礎練習、面試題

    java基礎練習、面試題整理了java私塾教材的課后作業,基礎部分,面試中也常常遇到的基礎問題,趕緊下載了。下載: [hide][/hide]
    發表于 07-16 14:02

    java經典面試題深度解析

    免費視頻教程:java經典面試題深度解析對于很多初學者來說,學好java在后期面試的階段都沒什么經驗,為了讓大家更好的了解面試相關知識,今天在這里給大家分享了一個java經典面試題深度
    發表于 06-20 15:16

    c語言面試題,c++面試題下載

    c語言面試題,c++面試題1. static有什么用途?(請至少說明兩種) 1) 限制變量的作用域 2) 設置變量的存儲域 2. 引用與指針有什么區別?  1) 引用必須被初
    發表于 10-22 11:19 ?5次下載

    c語言面試題

    c語言面試題集(單片機)C language problem(20151125084232)
    發表于 12-18 14:05 ?9次下載

    c語言面試題

    c語言面試題
    發表于 11-05 16:48 ?0次下載

    C語言經典面試題

    面試題
    發表于 12-20 22:41 ?0次下載

    C語言經典面試題

    C語言 經典面試題
    發表于 01-05 11:27 ?0次下載

    經典硬件面試題精選及解答

    經典硬件面試題精選及解答
    發表于 11-29 18:02 ?0次下載

    Java的經典面試題和答案詳細說明

    發現網上很多Java面試題都沒有答案,所以花了很長時間搜集整理出來了這套Java面試題大全,希望對大家有幫助哈~ 博主已將以下這些面試題整理成了一個Java面試手冊,題型非常全面附帶答
    發表于 09-07 08:00 ?0次下載
    Java的經典<b class='flag-5'>面試題</b>和答案詳細說明

    常見的MySQL高頻面試題

    在各類技術崗位面試中,似乎 MySQL 相關問題經常被問到。無論你面試開發崗位或運維崗位,總會問幾道數據庫問題。經常有小伙伴私信我,詢問如何應對 MySQL 面試題。其實很多面試題都是
    的頭像 發表于 02-08 16:05 ?2446次閱讀

    操作系統的四十多道題面試題

    ? 我之前匯總了一下關于操作系統的面試題,最近又重新翻閱了一下發現不是很全,現在也到了面試季了,所以我又花了一周的時間修訂整理了一下這份面試題,這份面試題可以吊打市面上所有的操作系統
    的頭像 發表于 03-10 10:17 ?3308次閱讀
    操作系統的四十多道題<b class='flag-5'>面試題</b>

    142道linux面試題,值得收藏

    142道linux面試題,值得收藏
    發表于 06-16 14:42 ?4次下載

    關于數組常見的面試題

    數組是最基本的數據結構,關于數組的面試題也屢見不鮮,本文羅列了一些常見的面試題,僅供參考。目前有以下18道題目。
    的頭像 發表于 08-17 09:25 ?1693次閱讀

    硬件工程師經典面試題詳解

    硬件工程師經典面試題詳解
    的頭像 發表于 11-20 15:08 ?1525次閱讀
    硬件工程師經典<b class='flag-5'>面試題</b>詳解
    自治县| 百家乐衬衣| 百家乐官网线路图分析| 月华百家乐官网的玩法技巧和规则 | 百利宫百家乐现金网| 金冠百家乐娱乐城| 太阳城百家乐外挂| 百家乐赌大小| 幸运水果机小游戏| 大发888游戏平台dafa 888 gw| bet365足球| 元阳县| 现场百家乐官网百家乐官网| 百家乐官网的规则博彩正网| 百家乐官网注册送彩金平台| 百家乐官网哪条路准| 反赌百家乐官网的玩法技巧和规则| 百家乐玩法及细则| 百家乐娱乐平台代理佣金| 新全讯网xb112| 365足球备用| 百家乐官网筹码订做| 百家乐官网网上赌局| 手机百家乐官网的玩法技巧和规则| 代理百家乐最多占成| 大哥大百家乐的玩法技巧和规则| 棋牌游戏平台有哪些| 百家乐官网终端下载| 蓝盾百家乐官网的玩法技巧和规则 | 百家乐官网视频双扣游戏| 百家乐官网多少钱| 百家乐路单破解软件| 全讯网77| 网上百家乐官网网址| 百家乐官网玩的技巧| 阴宅24层手机罗盘| 百家乐网哪一家做的最好呀| 伟博娱乐城| 至尊百家乐官网娱乐场| 百家乐筹码价格| 皇冠现金网安全吗|