C语言内存分配函数void* malloc(size_t size)的实际分配情况

本文探讨了C语言中malloc()函数在64位系统下内存分配的细节,包括最小分配块为32字节、对齐和overhead的影响。通过代码验证,解释了malloc(0)的分配情况,并强调了malloc()分配内存块中隐藏的overhead信息的重要性,提醒开发者应遵循malloc()的使用规范。
摘要由CSDN通过智能技术生成

系统信息:

$ lsb_release -a
No LSB modules are available.
Distributor ID:	elementary
Description:	elementary OS 0.4.1 Loki
Release:	0.4.1
Codename:	loki

$ uname -a         
Linux user 4.15.0-46-generic #49~16.04.1-Ubuntu SMP Tue Feb 12 17:45:24 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

$ cat /proc/version
Linux version 4.15.0-46-generic (buildd@lgw01-amd64-008) (gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.10)) #49~16.04.1-Ubuntu SMP Tue Feb 12 17:45:24 UTC 2019

查阅glibc里的malloc.c文件,里面介绍了malloc()在64位系统、size_t为8字节的情况下,最小分配块的大小是32字节。

//  glibc/malloc/malloc.c
/*
* Vital statistics:
  Supported pointer representation:       4 or 8 bytes
  Supported size_t  representation:       4 or 8 bytes
       Note that size_t is allowed to be 4 bytes even if pointers are 8.
       You can adjust this by defining INTERNAL_SIZE_T
  Alignment:                              2 * sizeof(size_t) (default)
       (i.e., 8 byte alignment with 4byte size_t). This suffices for
       nearly all current machines and C compilers. However, you can
       define MALLOC_ALIGNMENT to be wider than this if necessary.
 
  Minimum overhead per allocated chunk:   4 or 8 bytes
       Each malloced chunk has a hidden word of overhead holding size
       and status information.
 
  Minimum allocated size: 4-byte ptrs:  16 bytes    (including 4 overhead)
                          8-byte ptrs:  24/32 bytes (including, 4/8 overhead)
       When a chunk is freed, 12 (for 4byte ptrs) or 20 (for 8 byte
       ptrs but 4 byte size) or 24 (for 8/8) additional bytes are
       needed; 4 (8) for a trailing size field and 8 (16) bytes for
       free list pointers. Thus, the minimum allocatable size is
       16/24/32 bytes.
 
       Even a request for zero bytes (i.e., malloc(0)) returns a
       pointer to something of the minimum allocatable size.
 
*/

简单说,就是malloc(size)分配到的内存块,不单单是参数size指定的字节数这么简单,这个内存块的大小还受到(1)Alignment 对齐 == 2 * sizeof(size_t) ,(2)overhead 信息, 这两方面的共同约束。

所以&#

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值