如何在C中分配和释放对齐内存

发布于 2024-08-15 17:26:43 字数 238 浏览 7 评论 0原文

如何分配与 C 中的特定边界(例如缓存行边界)对齐的内存?我正在寻找类似 malloc/free 的实现,理想情况下应尽可能可移植——至少在 32 位和 64 位架构之间。

编辑添加:换句话说,我正在寻找一些行为类似于(现在已过时?) memalign功能,可以使用free释放。

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.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一场春暖 2024-08-22 17:26:43

这里有一个解决方案,它封装了对 malloc 的调用,分配一个更大的缓冲区用于对齐目的,并将原始分配的地址存储在对齐缓冲区之前,以便稍后调用 free。

// cache line
#define ALIGN 64

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

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

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**)((uintptr_t)(mem+ALIGN+sizeof(void*)) & ~(ALIGN-1));
    ptr[-1] = mem;
    return ptr;
}

void aligned_free(void *ptr) {
    free(((void**)ptr)[-1]);
}
メ斷腸人バ 2024-08-22 17:26:43

使用posix_memalign/免费

int posix_memalign(void **memptr, size_t alignment, size_t size); 

void* ptr;
int rc = posix_memalign(&ptr, alignment, size);
...
free(ptr)

posix_memalignmemalign 的标准替代品,正如您提到的那样,它已经过时了。

Use posix_memalign/free.

int posix_memalign(void **memptr, size_t alignment, size_t size); 

void* ptr;
int rc = posix_memalign(&ptr, alignment, size);
...
free(ptr)

posix_memalign is a standard replacement for memalign which, as you mention is obsolete.

绝對不後悔。 2024-08-22 17:26:43

你使用什么编译器?如果您使用的是 MSVC,则可以尝试 _aligned_malloc()_aligned_free()

What compiler are you using? If you're on MSVC, you can try _aligned_malloc() and _aligned_free().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文