c语言字节分配,由C语言中的malloc分配的意外输出大小

Michał Górny..

5

假设实现是glibc(或类似),可以在以下注释中找到以下内容malloc.c:

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.

这解释了开销的存在.

现在,对于'off by 1',标志对此负责.由于分配的大小(实际)malloc()将始终是8的倍数,因此三个最低有效位用于存储标志:

/* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */

#define PREV_INUSE 0x1

/* extract inuse bit of previous chunk */

#define prev_inuse(p) ((p)->size & PREV_INUSE)

/* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */

#define IS_MMAPPED 0x2

/* check for mmap()'ed chunk */

#define chunk_is_mmapped(p) ((p)->size & IS_MMAPPED)

/* size field is or'ed with NON_MAIN_ARENA if the chunk was obtained

from a non-main arena. This is only set immediately before handing

the chunk to the user, if necessary. */

#define NON_MAIN_ARENA 0x4

/* check for chunk from non-main arena */

#define chunk_non_main_arena(p) ((p)->size & NON_MAIN_ARENA)

编辑:啊,我差点忘了.大小存储为size_t,而不是int,因此您应该使用该类型来访问它.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值