C语言 在 GCC 中对齐 malloc()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3839922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
aligned malloc() in GCC?
提问by Dennis Yurichev
Is there any standardized function in GCC or glibc to allocate memory block at aligned pointer? Like _align_malloc()in MSVC?
GCC 或 glibc 中是否有任何标准化函数来在对齐的指针处分配内存块?像MSVC 中的_align_malloc()吗?
回答by Marc Glisse
Since the question was asked, a new function was standardized by C11:
自从问了这个问题,C11标准化了一个新函数:
void *aligned_alloc(size_t alignment, size_t size);
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 same freefunction as usual for deallocation.
它在 glibc 中可用(据我所知不在 Windows 上)。它以与 相同的顺序获取参数,与memalignMicrosoft 的相反_aligned_malloc,并使用与free通常相同的函数进行释放。
A subtle difference is that aligned_allocrequires sizeto be a multiple of alignment.
一个细微的区别是aligned_alloc需要size是 的倍数alignment。
回答by jschmier
The [
posix_memalign()][1] function provides aligned memory allocation and has been available since glibc 2.1.91.
[
posix_memalign()][1] 函数提供对齐的内存分配,从 glibc 2.1.91 开始可用。
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."
但不一定与其他编译器:引用标准“posix_memalign() 函数是咨询信息选项的一部分,不需要在所有实现中提供。”
回答by galinette
There are _mm_mallocand _mm_freewhich are supported by most compilers of the x86/x64 world, with at least:
有_mm_malloc与_mm_free它是由在x86 / x64世界上大多数编译器的支持,至少有:
- gcc
- MinGW (gcc win32/win64)
- MSVC
- clang
- ICC
- 海湾合作委员会
- MinGW (gcc win32/win64)
- MSVC
- 铛
- 国际商会
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:
AFAIK,这些功能根本不是标准。但据我所知,这是最受支持的。其他函数更特定于编译器:
- _aligned_malloc is MSVC and MinGW only
- posix memalign functions are not supported by at least MSVC
- _aligned_malloc 仅适用于 MSVC 和 MinGW
- 至少 MSVC 不支持 posix memalign 函数
There are also C11 standard functions but unfortunately they are not in c++11, and including them in c++ require non standard preprocessor defines...
还有 C11 标准函数,但不幸的是它们不在 c++11 中,并且将它们包含在 c++ 中需要非标准预处理器定义...
回答by AnT
It depends on what kind of alignment you expect. Do you want a stricter alignment, or a more relaxed alignment?
这取决于您期望的对齐方式。您想要更严格的对齐方式,还是更轻松的对齐方式?
mallocby 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?
malloc根据定义,保证返回一个正确对齐的指针,用于存储 C 程序中的任何标准类型(因此,任何从标准类型构建的类型)。这是您要找的吗?或者你需要不同的东西?

