在 GCC 中对齐 malloc() 吗?
GCC 或 glibc 中是否有标准化函数可以在对齐指针处分配内存块? 就像 _align_malloc()< /a> 在 MSVC 中?
Is there any standardized function in GCC or glibc to allocate memory block at aligned pointer?
Like _align_malloc() in MSVC?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
自从提出这个问题以来,C11 标准化了一个新函数:
并且它在 glibc 中可用(据我所知,在 Windows 上不可用)。它获取参数的顺序与
memalign
相同,与 Microsoft 的_aligned_malloc
相反,并使用与通常相同的free
函数进行释放。一个微妙的区别是,
aligned_alloc
要求size
是alignment
的倍数。Since the question was asked, a new function was standardized by C11:
and it is available in glibc (not on windows as far as I know). It takes its arguments in the same order as
memalign
, the reverse of Microsoft's_aligned_malloc
, and uses the samefree
function as usual for deallocation.A subtle difference is that
aligned_alloc
requiressize
to be a multiple ofalignment
.但不一定与其他编译器:引用标准
“posix_memalign() 函数是咨询信息选项的一部分,不需要在所有实现上提供。”
But not necessarily with other compilers: quoting the standard
"The posix_memalign() function is part of the Advisory Information option and need not be provided on all implementations."
x86/x64 世界的大多数编译器都支持
_mm_malloc
和_mm_free
,至少有:AFAIK,这些函数根本不是标准。但据我所知,这是最受支持的。其他函数更特定于编译器:
还有 C11 标准函数,但不幸的是它们不在 c++11 中,并且将它们包含在 c++ 中需要非标准预处理器定义...
There are
_mm_malloc
and_mm_free
which are supported by most compilers of the x86/x64 world, with at least:AFAIK, these functions are not a standard at all. But it is to my knowledge the most supported ones. Other functions are more compiler specific:
There are also C11 standard functions but unfortunately they are not in c++11, and including them in c++ require non standard preprocessor defines...
这取决于您期望什么样的对齐方式。您想要更严格的对齐,还是更宽松的对齐?
根据定义,malloc 保证返回一个正确对齐的指针,用于存储 C 程序中的任何标准类型(以及从标准类型构建的任何类型)。这是您正在寻找的吗?或者你需要一些不同的东西?
It depends on what kind of alignment you expect. Do you want a stricter alignment, or a more relaxed alignment?
malloc
by definition is guaranteed to return a pointer that is properly aligned for storing any standard type in C program (and, therefore, any type built from standard types). Is it what your are looking for? Or do you need something different?从 C11(和 C++17)开始,有标准库函数
aligned_alloc()
带签名:您必须
#include
才能使用它。size
参数必须是alignment
的倍数。失败时返回空指针。使用std::free()
释放分配的指针。尽管并非所有编译器都可能实现了这个标准函数。例如,MSVC 由于下一个原因没有实现它(请阅读 此处):
对于 MSVC
_aligned_malloc()
和_aligned_free()
必须使用。但是GCC/G++有这个标准的
aligned_alloc()
,至少我在Windows+Cygwin上测试过这个。Since C11 (and C++17) there is standard library function
aligned_alloc()
with signature:You must
#include <stdlib.h>
to use it. Thesize
parameter must be a multiple ofalignment
. On failure returns null pointer. Allocated pointer is freed usingstd::free()
.Although not all compilers may have implemented this standard function. For example MSVC didn't implement it for next reason (read here):
For MSVC
_aligned_malloc()
and_aligned_free()
must be used.But GCC/G++ has this standard
aligned_alloc()
, at least I tested this on Windows+Cygwin.