如何理解malloc的调整? [英] how does malloc understand alignment?

查看:126
本文介绍了如何理解malloc的调整?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面从这里摘录


  PW =(小部件*)malloc的(的sizeof(部件));


  
  

分配的原始存储。事实上,malloc调用分配存储空间
  这是足够大和对齐适当持有对象类型
  小部件


又见快速平普尔,他说:


  

对齐的。任何内存对齐。这是分配的任何内存
  动态的通过新的或malloc的是保证正确对齐作为
  任何类型的对象,但是缓冲器未动态分配
  有没有这样的保证。


我很好奇,怎样的malloc知道自定义类型的取向?


解决方案

对齐要求是递归的:任何对准结构只是其任何成员的最大对齐,这是递归理解

例如,假设每个基本类型的对齐等于它的大小(这不是一般总是如此),在结构X {INT;烧焦;双; } 的线形双,它会被填充为双(如4(int的长度的倍数),1(字符),3(填充),8(双))。在结构Ÿ{INT; X;浮动; } X ,这是最大的和等于的线形双和相应布局:4(INT),4(填充),16(X),4(浮点),4(填充)

(所有数字都只是例子,可能你的机器上有所不同。)

因此​​,通过将它分解为基本类型,我们只需要知道基本路线的少数,而那些中有一个著名的大。 C ++甚至定义了一个类型 maxalign_t (我认为),其排列的的那个最大的对齐方式。

所有的malloc()需要做的是选择就是这样值的倍数的地址。

following excerpted from here

pw = (widget *)malloc(sizeof(widget));

allocates raw storage. Indeed, the malloc call allocates storage that's big enough and suitably aligned to hold an object of type widget

also see fast pImpl from herb sutter, he said:

Alignment. Any memory Alignment. Any memory that's allocated dynamically via new or malloc is guaranteed to be properly aligned for objects of any type, but buffers that are not allocated dynamically have no such guarantee

I am curious about this, how does malloc know alignment of the custom type?

解决方案

Alignment requirements are recursive: The alignment of any struct is simply the largest alignment of any of its members, and this is understood recursively.

For example, and assuming that each fundamental type's alignment equals its size (this is not always true in general), the struct X { int; char; double; } has the alignment of double, and it will be padded to be a multiple of the size of double (e.g. 4 (int), 1 (char), 3 (padding), 8 (double)). The struct Y { int; X; float; } has the alignment of X, which is the largest and equal to the alignment of double, and Y is laid out accordingly: 4 (int), 4 (padding), 16 (X), 4 (float), 4 (padding).

(All numbers are just examples and could differ on your machine.)

Therefore, by breaking it down to the fundamental types, we only need to know a handful of fundamental alignments, and among those there is a well-known largest. C++ even defines a type maxalign_t (I think) whose alignment is that largest alignment.

All malloc() needs to do is to pick an address that's a multiple of that value.

这篇关于如何理解malloc的调整?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆