约 2484 字

约 12 分钟

#C 语言标准库函数 aligned_alloc

/*********************************************
 * @brief 分配对齐的内存
 * @param alignment 对齐的字节数
 * @param size 分配的内存字节数
 * @return 分配的内存地址
 ********************************************/
void* aligned_alloc(size_t alignment, size_t size);

说明

分配 size 字节的内存,按照 alignment 字节对齐(地址是 alignment 的整数倍),内存中的数据不会初始化,返回该内存的地址。

返回的指针需要通过 free 进行释放。

注意:

  • 如果 alignment 值不被支持,将会失败并返回 NULL
  • size 应当是 alignment 的整数倍,否则可能失败并返回 NULL

参数

  • alignment - 要对齐的字节数
  • size - 要分配的字节数,应当是 alignment 的整数倍

返回值

  • 返回分配的内存地址
  • 失败时返回 NULL

#示例

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stddef.h>

int main(void)
{
    int* ptr1 = (int*) malloc(1024 * sizeof(int));  // 分配内存,1024 个 int
    printf("默认(%zu 字节)对齐分配的地址:%p / 1204 = %f\n", alignof(max_align_t), ptr1, (uintptr_t)ptr1 / 1024.0);     // 地址不一定能整除 1024
    free(ptr1);     // 释放内存

    int* ptr2 = (int*) aligned_alloc(1024, 1024 * sizeof(int));  // 分配内存,1024 个 int
    printf("1024 字节对齐分配的地址:%p / 1204 = %f\n", ptr2, (uintptr_t)ptr2 / 1024.0);    // 地址可以整除 1024
    free(ptr2);     // 释放内存
    
    return 0;
}

运行结果:

默认(16 字节)对齐分配的地址:0x5a6b725092a0 / 1204 = 97087427620.656250
1024 字节对齐分配的地址:0x5a6b72509800 / 1204 = 97087427622.000000

#推荐阅读

#参考标准

  • C23 standard (ISO/IEC 9899:2024):
    • 7.22.3.1 The aligned_alloc function (p: TBD)
  • C17 standard (ISO/IEC 9899:2018):
    • 7.22.3.1 The aligned_alloc function (p: 253)
  • C11 standard (ISO/IEC 9899:2011):
    • 7.22.3.1 The aligned_alloc function (p: 347-348)

更新: 2025/10/25

作者: PlanC

创建: 2025/7/26