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) 这种故意挑事的代码,实现时可以返回一个空指针作为回礼。


声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • 程序
    +关注

    关注

    114

    文章

    3631

    浏览量

    79541
  • 源代码
    +关注

    关注

    94

    文章

    2927

    浏览量

    66063
  • Glibc
    +关注

    关注

    0

    文章

    9

    浏览量

    7471
  • malloc
    +关注

    关注

    0

    文章

    52

    浏览量

    38

原文标题:面试题:malloc(0)会发生什么?

文章出处:【微信号:c-stm32,微信公众号:STM32嵌入式开发】欢迎添加关注!文章转载请注明出处。

收藏 人收藏

    评论

    相关推荐

    常见的嵌入式C语言面试题

    数组是最基本的数据结构,关于数组的面试题也屡见不鲜,本文罗列了一些常见的面试题,仅供参考。目前有以下18道题目。
    发表于 07-18 10:46 590次阅读

    java基础练习、面试题

    java基础练习、面试题整理了java私塾教材的课后作业,基础部分,面试中也常常遇到的基础问题,赶紧下载了。下载: [hide][/hide]
    发表于 07-16 14:02

    FPGA笔试面试题

    FPGA笔试面试题
    发表于 08-07 21:54

    经典嵌入式面试题

    经典嵌入式面试题
    发表于 08-20 09:39

    java经典面试题深度解析

    免费视频教程:java经典面试题深度解析对于很多初学者来说,学好java在后期面试的阶段都没什么经验,为了让大家更好的了解面试相关知识,今天在这里给大家分享了一个java经典面试题深度
    发表于 06-20 15:16

    NLP的面试题

    NLP面试题目6-10
    发表于 05-21 15:02

    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 8次下载

    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次下载

    常见的MySQL高频面试题

    在各类技术岗位面试中,似乎 MySQL 相关问题经常被问到。无论你面试开发岗位或运维岗位,总会问几道数据库问题。经常有小伙伴私信我,询问如何应对 MySQL 面试题。其实很多面试题都是
    的头像 发表于 02-08 16:05 2074次阅读

    142道linux面试题,值得收藏

    142道linux面试题,值得收藏
    发表于 06-16 14:42 3次下载

    关于数组常见的面试题

    数组是最基本的数据结构,关于数组的面试题也屡见不鲜,本文罗列了一些常见的面试题,仅供参考。目前有以下18道题目。
    的头像 发表于 08-17 09:25 1208次阅读