malloc内存分配字节对齐问题

本文探讨了C/C++中内存分配的字节对齐问题,特别是在高并发和资源优化系统中的重要性。通过分析glibc的malloc.c,了解到对齐参数必须是2的幂且为void *的整数倍。例如,在64位系统中,申请25字节内存将消耗48字节。此外,分享了一篇关于如何实现简单malloc函数的文章。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近看了一些开源的C/C++库,其中都对于内存分配这块做出了自己的一些优化和说明,也涉及到了一些内存分配字节对齐以及内存分页的问题。

对于内存分配的字节对齐问题,一直都是只知其事,不知其解,平时也很少关注这一块会带来的性能问题。但是要是放在一个高并发,快速以及资源最大化利用的系统里面,这一块往往是需要注意的,所以也就趁着这次机会,大概的了解一下。

我们先来看一下glibc里面malloc.c的定义

1100 /*
1101   -----------------------  Chunk representations -----------------------
1102 */
1103 
1104 
1105 /*
1106   This struct declaration is misleading (but accurate and necessary).
1107   It declares a "view" into memory allowing access to necessary
1108   fields at known offsets from a given base. See explanation below.
1109 */
1110 
1111 struct malloc_chunk {
1112 
1113   INTERNAL_SIZE_T      prev_size;  /* Size of previous chunk (if free).  */
1114   INTERNAL_SIZE_T      size;       /* Size in bytes, including overhead. */
1115 
1116   struct malloc_chunk* fd;         /* double links -- used only if free. */
1117   struct malloc_chunk* bk;
1118 
1119   /* Only used for large blocks: pointer to next larger size.  */
1120   struct malloc_chunk* fd_nextsize; /* double links -- used only if free. */
1121   struct malloc_chunk* bk_nextsize;
1122 };
1123 
1124 
1125 /*
1126    malloc_chunk details:
1127 
1128     (The following includes lightly edited explanations by Colin Plumb.)
1129 
1130     Chunks of memory are maintained using a `boundary tag' method as
1131     described in e.g., Knuth or Standish.  (See the paper by Paul
1132     Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
1133     survey of such techniques.)  Sizes of free chunks are stored both
1134     in the front of each chunk and at the end.  This makes
1135     consolidating fragmented chunks into bigger chunks very fast.  The
1136     size fields also hold bits representing whether c
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值