如何字节对齐使用malloc()完成? [英] How is byte alignment done with malloc()?

查看:1291
本文介绍了如何字节对齐使用malloc()完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在读用来对准内存分配和释放分配的内存的程序。这里是C code:

I am currently reading a program used to aligned memory allocation and free allocated memory. Here is the C code:

/**
 * Aligned memory allocation
 * param[in] size Bytes to be allocated
 * param[in] alignment Alignment bytes
 * return Address of allocated memory
 */
inline void* _al_malloc(size_t size, size_t alignemt)
{
    size_t a = alignment - 1;
    size_t word_length = sizeof(void*);
    void* raw = malloc(word_length + size + a);
    if (!raw)
    {
        return 0;
    }
    void* ptr = (void*)((size_t(raw) + word_length + a) & ~a);
    *((void**)ptr - 1) = raw;
    return ptr;
}



/**
 * Free allocated memory
 */
inline void _al_free(void * ptr)
{
    if (!ptr)
    {
        return;
    }
    void* raw = *((void**)ptr - 1);
    free(raw);
}

如何执行这些操作保证字节对齐的内存?

How do these operations ensure byte aligned memory?

推荐答案

它分配额外的内存,然后使其正确对齐移动返回指针的起始地址(通过可能留下几个字节未使用)。

It allocates extra memory, and then moves the start address of the returned pointer so that it is properly aligned (by possibly leaving a few bytes unused).

更详细的:

size_t a = alignment - 1;

如果对准是2的幂,这样会给的需要额外的字节的数量和用于以对准指针不允许地址位的掩模。

If alignment is a power of 2, this will give both the number of extra bytes needed and a mask for address bits not allowed in an aligned pointer.

例如,如果对齐方式为8,我们可能需要分配7额外字节,以确保其中之一是在8对齐。

For example, if alignment is 8 we might need to allocate 7 extra bytes to be sure that one of them is aligned at 8.

size_t word_length = sizeof(void*);

计算额外的指针的大小(以免费需要更高版本)。

void* raw = malloc(word_length + size + a);

分配一个指针+额外的字节,我们可能需要对齐的所需的内存块+大小。

Allocate the needed memory block + size of a pointer + extra bytes we might need for alignment.

if (!raw)
{
    return 0;
}

返回一个空指针如果我们失败。

Return a null pointer if we fail.

void* ptr = (void*)((size_t(raw) + word_length + a) & ~a);

现在得到一个新的指针,它是原始指针+空间节省+所需的正确的对准的字节数。

Now get a new pointer that is the raw pointer + space for saving + the number of bytes needed for proper alignment.

*((void**)ptr - 1) = raw;

还可以节省从的malloc 原来的指针,东阳是需要的免费后来。

Also save the original pointer from malloc, beacause that is needed to free it later.

return ptr;

完成。

这篇关于如何字节对齐使用malloc()完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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