GCC 4.7 開始實驗性支持 C11,**但特性支持是逐個函數/語法塊推進的**,並非整體切換。aligned_alloc 直到 GCC 8.1 才完整實現(參考 GCC C11 Status)。
| GCC 版本 | aligned_alloc 支持 | 備註 |
|---|---|---|
| < 8.1 | 不支持 / 部分支持 | 可能需 __builtin_assume_aligned 或 POSIX posix_memalign |
| 8.1 - 9.x | 支持 (需 -std=c11 或 -std=gnu11) | 仍可能受 libc 限制 (glibc 2.16+) |
| 10+ | 完善 | 配合 stdalign.h 更佳 |
// POSIX 標準,Linux/macOS/Windows (MSVC 2017+) 均支持
void *ptr = NULL;
int ret = posix_memalign(&ptr, alignment, size);
if (ret != 0) ptr = NULL;
// C++17 標準庫 (推薦 C++ 項目)
#include <memory>
void *ptr = std::aligned_alloc(alignment, size); // C++17
// 或
auto ptr = std::malloc(size); // 手動對齊 (C++11)
即使編譯器支持,運行時 C 庫 (glibc, musl, MSVCRT) 也必須提供符號。嵌入式交叉編譯工具鏈常見「編譯通過、鏈接失敗」。