如何分配和C语言免费对齐的内存 [英] How to allocate and free aligned memory in C

查看:251
本文介绍了如何分配和C语言免费对齐的内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你怎么分配多数民众赞成对齐到特定边界C(例如,高速缓存行边界)的内存?我正在寻找的malloc /免费的像实施,理想将尽可能实现可移植性---至少在32位和64位架构。

How do you allocate memory that's aligned to a specific boundary in C (e.g., cache line boundary)? I'm looking for malloc/free like implementation that ideally would be as portable as possible --- at least between 32 and 64 bit architectures.

编辑补充:换句话说,我在寻找的东西会表现得像是的 memalign可功能,可以使用免费的释放。

Edit to add: In other words, I'm looking for something that would behave like (the now obsolete?) memalign function, which can be freed using free.

推荐答案

下面是一个解决方案,它封装在调用malloc的,分配的调整目的更大的缓冲区,只为一对准缓冲区之前存储原始分配的地址后来打电话来释放。

Here is a solution, which encapsulates the call to malloc, allocates a bigger buffer for alignment purpose, and stores the original allocated address just before the aligned buffer for a later call to free.

// cache line
#define ALIGN 64

void *aligned_malloc(int size) {
    void *mem = malloc(size+ALIGN+sizeof(void*));
    void **ptr = (void**)((long)(mem+ALIGN+sizeof(void*)) & ~(ALIGN-1));
    ptr[-1] = mem;
    return ptr;
}

void aligned_free(void *ptr) {
    free(((void**)ptr)[-1]);
}

这篇关于如何分配和C语言免费对齐的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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