c - malloc 对内存对齐有哪些保证?

标签 c memory-management malloc

我遇到了以下代码:

int main()
{
    char *A=(char *)malloc(20);
    char *B=(char *)malloc(10);
    char *C=(char *)malloc(10);
    printf("\n%d",A);
    printf("\t%d",B);
    printf("\t%d\n",C);
    return 0;
}  
//output--   152928264     152928288    152928304

我想知道分配和填充是如何通过malloc()完成的。查看输出可以看出起始地址是8的倍数,还有其他规则吗?

最佳答案

根据this documentation page ,

the address of a block returned by malloc or realloc in the GNU system is always a multiple of eight (or sixteen on 64-bit systems).

通常,malloc 实现是系统特定的。它们都为自己的簿记保留一些内存(例如,分配 block 的实际长度),以便在您调用 free 时能够正确释放该内存。如果您需要对齐到特定边界,请使用其他功能,例如 posix_memalign .

关于c - malloc 对内存对齐有哪些保证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8575822/

相关文章:

c - 使用 dlinfo 打印库中的所有符号

c - 释放可变参数函数中的所有参数

c - 这会被认为是内存泄漏吗?

c - 函数内部使用malloc形成字符串时的段错误(11)

c - 如何调整CRC32与CRC16的调节因子计算?

c - 如何在 dbx 中打印长字符串的完整值?

c - 'Memory allocation'在C中的用途是什么?

c++ - 对象数组的插入方法c++

c - realloc:释放对象的无效校验和

c - Linux环境下malloc杀死子进程